在 go 反射包中,调用 Value.Kind() 是 Value.Type().Kind()

这两个的reflect.Type接口和reflect.Value类型实现了相同的Kind()方法签名,假设我们有一定的价值目标v := reflect.ValueOf(x)

v.Kind()只需要调用v.Type().Kind()


宝慕林4294392
浏览 417回答 2
2回答

心有法竹

它们包含相同的值,但似乎不是指同一件事:type.go源码value.go源码AType通常由未导出的结构rtype(via TypeOf)实现,而Value包含 a*rtype和 extends flag,它本身是 的简化形式Kind:// flag holds metadata about the value.// The lowest bits are flag bits://&nbsp; - flagRO: obtained via unexported field, so read-only//&nbsp; - flagIndir: val holds a pointer to the data//&nbsp; - flagAddr: v.CanAddr is true (implies flagIndir)//&nbsp; - flagMethod: v is a method value.// The next five bits give the Kind of the value.// This repeats typ.Kind() except for method values.// The remaining 23+ bits give a method number for method values.// If flag.kind() != Func, code can assume that flagMethod is unset.// If typ.size > ptrSize, code can assume that flagIndir is set.拿到ValueOf东西时:// ValueOf returns a new Value initialized to the concrete value// stored in the interface i.&nbsp; ValueOf(nil) returns the zero Value.func ValueOf(i interface{}) Value {&nbsp; &nbsp; [...]&nbsp; &nbsp; // For an interface value with the noAddr bit set,&nbsp; &nbsp; // the representation is identical to an empty interface.&nbsp; &nbsp; eface := *(*emptyInterface)(unsafe.Pointer(&i))&nbsp; &nbsp; typ := eface.typ&nbsp; &nbsp; /** Flag is built from the type, then kept separate (my comment) */&nbsp; &nbsp; fl := flag(typ.Kind()) << flagKindShift&nbsp; &nbsp; if typ.size > ptrSize {&nbsp; &nbsp; &nbsp; &nbsp; fl |= flagIndir&nbsp; &nbsp; }&nbsp; &nbsp; return Value{typ, unsafe.Pointer(eface.word), fl}}所以当你得到一个 Value 类型时(记住它扩展了它的标志):func (v Value) Kind() Kind {&nbsp; &nbsp; return v.kind()}func (f flag) kind() Kind {&nbsp; &nbsp; return Kind((f >> flagKindShift) & flagKindMask)}同时获取一种类型:(Type是一个接口,通常由 实现*rtype)func (t *rtype) Kind() Kind { return Kind(t.kind & kindMask) }因此,尽管他们似乎是在大多数的情况下平等,v.Kind()是不 v.Type().Kind()

跃然一笑

文件reflect/value.go声明reflect.Value“重复typ.Kind() 除了方法值”的实现中的相关字段。所以,除非值是一个方法,value.Kind()并且value.Type().Kind()返回相同的数字。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go