reflect.UnsafeAddr() Function in Golang with Examples
Last Updated :
12 Dec, 2021
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.UnsafeAddr() Function in Golang is used to get the pointer to v’s data. To access this function, one needs to imports the reflect package in the program.
Syntax:
func (v Value) UnsafeAddr() uintptr
Parameters: This function does not accept any parameter.
Return Value: This function returns the pointer to v’s data.
Below examples illustrate the use of the above method in Golang:
Example 1:
C
package main
import (
"fmt"
"reflect"
"unsafe"
)
func main() {
var s = struct { foo int }{42}
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)
fmt.Println(ri)
}
|
Output:
42
42
Example 2:
C
package main
import (
"fmt"
"reflect"
"unsafe"
)
func main() {
var s = struct { foo int }{374}
var i int
rs := reflect.ValueOf(s)
rf := rs.Field(0)
rs2 := reflect.New(rs.Type()).Elem()
rs2.Set(rs)
rf = rs2.Field(0)
rf = reflect.NewAt(rf.Type(), unsafe.Pointer(rf.UnsafeAddr())).Elem()
ri := reflect.ValueOf(&i).Elem()
ri.Set(rf)
fmt.Println(rf)
fmt.Println(ri)
}
|
Output:
374
374
Share your thoughts in the comments
Please Login to comment...