📜  Golang 中的reflect.CanAddr()函数示例

📅  最后修改于: 2021-10-24 14:11:18             🧑  作者: Mango

Go 语言提供了运行时反射的内置支持实现,并允许程序在反射包的帮助下操作任意类型的对象。 Golang 中的reflect.CanAddr()函数用于检查是否可以通过Addr 获取值的地址。要访问此函数,需要在程序中导入反射包。

下面的例子说明了上述方法在 Golang 中的使用:

示例 1:

func (v Value) CanAddr() bool

输出:

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

示例 2:

value: true

输出:

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