reflect.NewAt() Function in Golang with Examples
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.NewAt() Function in Golang is used to get the Value representing a pointer to a value of the specified type, using p as that pointer. To access this function, one needs to imports the reflect package in the program.
Syntax:
func NewAt(typ Type, p unsafe.Pointer) Value
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.
Below examples illustrate the use of the above method in Golang:
Example 1:
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()
rf = reflect.NewAt(rf.Type(), unsafe.Pointer(rf.UnsafeAddr())).Elem()
ri.Set(rf)
rf.Set(ri)
fmt.Println(rf)
}
|
Output:
100
Example 2:
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
}
|
Output:
Old Value
New Value
Last Updated :
03 May, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...