Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

reflect.CanAddr() Function in Golang with Examples

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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.CanAddr() Function in Golang is used to check whether the value’s address can be obtained with Addr. To access this function, one needs to imports the reflect package in the program.

Syntax:

func (v Value) CanAddr() bool

Parameters: This function does not accept any parameters.

Return Value: This function returns the boolean value.

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

Example 1:




// Golang program to illustrate
// reflect.CanAddr() 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.CanAddr()
    fmt.Printf("value: %+v\n", s)
}         

Output:

value: true

Example 2:




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

Output:

{1 9} 
true 

My Personal Notes arrow_drop_up
Last Updated : 03 May, 2020
Like Article
Save Article
Similar Reads