reflect.Addr() Function in Golang with Examples
Last Updated :
03 May, 2020
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.Addr() Function in Golang is used to get the pointer value representing the address of v. To access this function, one needs to imports the reflect package in the program.
Syntax:
func (v Value) Addr() Value
Parameters: This function does not accept any parameters.
Return Value: This function returns the pointer value representing the address of v.
Below examples illustrate the use of the above method in Golang:
Example 1:
package main
import (
"fmt"
"reflect"
)
func main() {
typ := reflect.StructOf([]reflect.StructField{
{
Name: "Height" ,
Type: reflect.TypeOf(float64(0)),
Tag: `json: "height" `,
},
{
Name: "Age" ,
Type: reflect.TypeOf( int (0)),
Tag: `json: "age" `,
},
})
v := reflect.New(typ).Elem()
v.Field(0).SetFloat(0.4)
v.Field(1).SetInt(2)
s := v.Addr().Interface()
fmt.Printf( "value: %+v\n" , s)
}
|
Output:
value: &{Height:0.4 Age:2}
Example 2:
package main
import (
"fmt"
"reflect"
)
type superint struct {
A int
B int
}
func (s *superint) lol() {}
type a interface{ lol() }
func main() {
i := superint{A: 1, B: 9}
valPtr := reflect.ValueOf(&i)
fmt.Printf( "%v \n" , i.A)
fmt.Printf( "%v \n" , valPtr.Elem().Addr().Interface())
}
|
Output:
1
&{1 9}
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...