Golang reflect.NewAt()函数及示例

Golang reflect.NewAt()函数及示例

Go语言提供了内置支持运行时反射实现,并借助reflect包允许程序操作任意类型的对象。 Golang中的 reflect.NewAt() 函数用于获取表示指向特定类型值的指针的值,使用p作为该指针。要访问此函数,需要在程序中导入reflect包。

语法:

func NewAt(typ Type, p unsafe.Pointer) Value

参数: 此函数接受以下参数:

  • typ: 此参数为Type类型。
  • p: 此参数为unsafe.Pointer类型。

返回值: 此函数返回表示指向指定类型值的指针的值(Value类型)。

以下示例演示以上方法在Golang中的使用:

示例1:

// Golang程序演示
// reflect.NewAt()函数

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()
      
    // 使用NewAt()方法
    rf = reflect.NewAt(rf.Type(), unsafe.Pointer(rf.UnsafeAddr())).Elem()
    ri.Set(rf)
    rf.Set(ri)
      
    fmt.Println(rf)
} 

输出:

100

示例2:

// Golang程序演示
// reflect.NewAt()函数

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
} 

输出:

Old Value 
New Value

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程