Go 语言提供了运行时反射的内置支持实现,并允许程序在反射包的帮助下操作任意类型的对象。 Golang 中的reflect.Pointer()函数用于获取v 的值作为uintptr。要访问此函数,需要在程序中导入反射包。
Syntax:
Parameters: This function does not accept any parameter.
Return Value: This function returns the v’s value as a uintptr.
下面的例子说明了上述方法在 Golang 中的使用:
示例 1:
func (v Value) Pointer() uintptr
输出:
// Golang program to illustrate
// reflect.Pointer() Function
package main
import (
"reflect"
"unsafe"
"fmt"
)
func main() {
var s = struct{ foo int }{100}
var i int
rs := reflect.ValueOf(&s).Elem()
rf := rs.Field(0)
ri := reflect.ValueOf(&i).Elem()
// use of Pointer() method
rf = reflect.NewAt(rf.Type(), unsafe.Pointer(rf.UnsafeAddr())).Elem()
ri.Set(rf)
rf.Set(ri)
fmt.Println(rf)
}
示例 2:
100
输出:
// Golang program to illustrate
// reflect.Pointer() Function
package main
import (
"fmt"
"play.ground/foo"
"reflect"
"unsafe"
)
func GetUnexportedField(field reflect.Value) interface{} {
return reflect.NewAt(field.Type(), unsafe.Pointer(field.UnsafeAddr())).Elem().Interface()
}
func SetUnexportedField(field reflect.Value, value interface{}) {
reflect.NewAt(field.Type(), unsafe.Pointer(field.UnsafeAddr())).
Elem().
Set(reflect.ValueOf(value))
}
func main() {
f := &foo.Foo{
Exported: "Old Value ",
}
fmt.Println(f.Exported)
field := reflect.ValueOf(f).Elem().FieldByName("unexported")
SetUnexportedField(field, "New Value")
fmt.Println(GetUnexportedField(field))
}
-- go.mod --
module play.ground
-- foo/foo.go --
package foo
type Foo struct {
Exported string
unexported string
}