Go 语言提供了运行时反射的内置支持实现,并允许程序在反射包的帮助下操作任意类型的对象。 Golang 中的reflect.NewAt()函数用于获取表示指向指定类型值的指针的Value,使用p 作为该指针。要访问此函数,需要在程序中导入反射包。
Syntax:
Parameters: This function takes the following parameters:
- typ : This parameter is the Type.
- p : This parameter is the unsafe.Pointer.
Return Value: This function returns a Value representing a pointer to a value of the specified type.
下面的例子说明了上述方法在 Golang 中的使用:
示例 1:
func NewAt(typ Type, p unsafe.Pointer) Value
输出:
// Golang program to illustrate
// reflect.NewAt() 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 NewAt() 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.NewAt() 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
}