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() uintptrParameters: 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:
// Golang program to illustrate // reflect.UnsafeAddr() Function package main import ( "fmt"
"reflect"
"unsafe"
) // Main function 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:
// Golang program to illustrate // reflect.UnsafeAddr() Function package main import ( "fmt"
"reflect"
"unsafe"
) // Main function 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() // i, but writable
ri.Set(rf)
fmt.Println(rf)
fmt.Println(ri)
} |
Output:
374 374