reflect.CanAddr() 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.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() boolParameters: 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
Please Login to comment...