当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


Golang reflect.Pointer()用法及代码示例

Go语言提供了运行时反射的内置支持实现,并允许程序借助反射包来操纵任意类型的对象。 Golang中的reflect.Pointer()函数用于获取v的uintptr值。要访问此函数,需要在程序中导入反射包。

用法:
func (v Value) Pointer() uintptr

参数:此函数不接受任何参数。

返回值:该函数返回五世的值作为uintptr。

以下示例说明了以上方法在Golang中的用法:



范例1:

// 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) 
}

输出:

100

范例2:

// 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 
}

输出:

Old Value 
New Value



相关用法


注:本文由纯净天空筛选整理自SHUBHAMSINGH10大神的英文原创作品 reflect.Pointer() Function in Golang with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。