Skip to content
Related Articles

Related Articles

Improve Article

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:




// Golang program to illustrate
// reflect.Addr() Function
   
package main
   
import (
    "fmt"
    "reflect"
)
   
// Main function 
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:




// Golang program to illustrate
// reflect.Addr() Function
   
package main
   
import (
    "fmt"
    "reflect"
)
   
// Main function 
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)
  
    // use of Addr() method
    fmt.Printf("%v \n", valPtr.Elem().Addr().Interface())
}

Output:

1 
&{1 9} 



My Personal Notes arrow_drop_up
Recommended Articles
Page :