Open In App

reflect.UnsafeAddr() Function in Golang with Examples

Last Updated : 12 Dec, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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




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

C




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


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads