Golang reflect.CanAddr()函数的使用方式及示例
Go 语言提供运行时反射的内置支持,在 reflect 包的帮助下可以让程序操作任意类型的对象。 Golang 中的 reflect.CanAddr() 函数用于检查是否可以使用 Addr 获取值的地址。要访问此函数,需要在程序中导入 reflect 包。
语法:
func (v Value) CanAddr() bool
参数:
此函数不接受任何参数。
返回值:
该函数返回布尔值。
以下示例演示了 Golang 中上述方法的用法:
示例1:
// Golang程序演示
// reflect.CanAddr()函数
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.CanAddr()
fmt.Printf("value: %+v\n", s)
} ```
输出:
value: true
示例 2:
// Golang程序演示
// reflect.CanAddr()函数
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)
//使用Addr()方法
fmt.Printf("%v \n", valPtr.Elem().CanAddr())
}
输出:
{1 9}
true
极客教程