reflect.Pointer() 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.Pointer() Function in Golang is used to get the v’s value as a uintptr. To access this function, one needs to imports the reflect package in the program.

Syntax:

func (v Value) Pointer() uintptr

Parameters: This function does not accept any parameter.

Return Value: This function returns the v’s value as a uintptr.

Below examples illustrate the use of the above method in Golang:



Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

100

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

Old Value 
New Value



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.