Golang reflect.Set()函数及示例
Go语言提供了runtime reflection的内置支持,通过reflect包,使程序能够操作任意类型的对象。Golang中的 reflect.Set() 函数用于将x赋值给v。要使用此函数,需要在程序中引入reflect包。
语法:
func (v Value) Set(x Value)
参数: 此函数接受一个Value类型的参数 (x)。
返回值: 此函数不返回任何值。
下面的示例说明了在Golang中使用上述方法的用法:
示例 1:
// Golang程序,演示
// reflect.Set()函数
package main
import (
"fmt"
"reflect"
"unsafe"
)
// 主函数
func main() {
var s = struct{ foo int }{654}
var i int
rs := reflect.ValueOf(&s).Elem()
rf := rs.Field(0)
ri := reflect.ValueOf(&i).Elem()
rf = reflect.NewAt(rf.Type(), unsafe.Pointer(rf.UnsafeAddr())).Elem()
ri.Set(rf)
rf.Set(ri)
fmt.Println(rf)
fmt.Println(ri)
}
输出:
654
654
示例 2:
// Golang程序,演示
// reflect.Set()函数
package main
import (
"fmt"
"reflect"
)
func sum(args []reflect.Value) []reflect.Value {
a, b := args[0], args[1]
if a.Kind() != b.Kind() {
fmt.Println("??? ????.")
return nil
}
switch a.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16,
reflect.Int32, reflect.Int64:
return []reflect.Value{reflect.ValueOf(a.Int() + b.Int())}
case reflect.Uint, reflect.Uint8, reflect.Uint16,
reflect.Uint32, reflect.Uint64:
return []reflect.Value{reflect.ValueOf(a.Uint() + b.Uint())}
case reflect.Float32, reflect.Float64:
return []reflect.Value{reflect.ValueOf(a.Float() + b.Float())}
case reflect.String:
return []reflect.Value{reflect.ValueOf(a.String() + b.String())}
default:
return []reflect.Value{}
}
}
func makeSum(fptr interface{}) {
fn := reflect.ValueOf(fptr).Elem()
v := reflect.MakeFunc(fn.Type(), sum)
fn.Set(v)
}
// 主函数
func main() {
var stringSum func(string, string) string
makeSum(&stringSum)
fmt.Println(stringSum("Value_1 : ", "Geeks_1"))
}
输出:
Value_1 : Geeks_1