gpt4 book ai didi

go - 为什么 Go reflect NumField() 只能在类型上可用?

转载 作者:数据小太阳 更新时间:2023-10-29 03:40:52 25 4
gpt4 key购买 nike

我有以下 Go 代码 ( play.golang.org ):

package main

import (
"reflect"
"fmt"
)

type User struct {
name string
email string
}

func main() {
uS := User{}
uSt := reflect.TypeOf(uS)

fmt.Println( uSt )
fmt.Println( uSt.NumField() )
// fmt.Println( uS.NumField() ) // this doesn't work, why?

}

我只是好奇这里。为什么我们需要在调用 NumField() 之前先获取结构的类型?

为什么我们不能只在结构本身上调用它,即 uS.NumField()

来自 docs :

type Value struct {
// contains filtered or unexported fields
}

func (v Value) NumField() int

我不太明白 Value 在这里的真正含义。我非常感谢简洁的解释和示例。

最佳答案

TypeOf returns the reflection Type that represents the dynamic type of i. If i is a nil interface value, TypeOf returns nil.

从上面的语句可以清楚地看出 TypeOf 返回 reflection Type

func TypeOf(i interface{}) Type // return reflection type

反射类型在 Golang 中定义为

Type is the representation of a Go type. Type values are comparable, such as with the == operator, so they can be used as map keys.

Value 是 Go 值的反射接口(interface),您将其用于 Numfield 方法作为接收者。正如@Flimzy 所述,对于任何其他反射方法,您还需要使用反射值。

在您的代码中:

uS := User{}
uSt := reflect.TypeOf(uS)

第一个值 us 被分配给用户类型结构。而第二个值 uStreflect.TypeOf 的返回值分配为 reflection Type。检查每个变量的类型:

package main

import (
"reflect"
"fmt"
)

type User struct {}

func main() {
uS := User{}
uSt := reflect.TypeOf(uS)
fmt.Printf("%T\n", uS) // Print the type of uS
fmt.Printf("%T\n", uSt)
}

输出

main.User
*reflect.rtype

Playground Example

有关反射如何工作的更多信息。通过Laws of Reflection

关于go - 为什么 Go reflect NumField() 只能在类型上可用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51474409/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com