2 回答

TA貢獻(xiàn)1866條經(jīng)驗(yàn) 獲得超5個(gè)贊
它們包含相同的值,但似乎不是指同一件事:
type.go源碼
value.go源碼
AType通常由未導(dǎo)出的結(jié)構(gòu)rtype(via TypeOf)實(shí)現(xiàn),而Value包含 a*rtype和 extends flag,它本身是 的簡化形式Kind:
// flag holds metadata about the value.
// The lowest bits are flag bits:
// - flagRO: obtained via unexported field, so read-only
// - flagIndir: val holds a pointer to the data
// - flagAddr: v.CanAddr is true (implies flagIndir)
// - 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東西時(shí):
// ValueOf returns a new Value initialized to the concrete value
// stored in the interface i. ValueOf(nil) returns the zero Value.
func ValueOf(i interface{}) Value {
[...]
// For an interface value with the noAddr bit set,
// the representation is identical to an empty interface.
eface := *(*emptyInterface)(unsafe.Pointer(&i))
typ := eface.typ
/** Flag is built from the type, then kept separate (my comment) */
fl := flag(typ.Kind()) << flagKindShift
if typ.size > ptrSize {
fl |= flagIndir
}
return Value{typ, unsafe.Pointer(eface.word), fl}
}
所以當(dāng)你得到一個(gè) Value 類型時(shí)(記住它擴(kuò)展了它的標(biāo)志):
func (v Value) Kind() Kind {
return v.kind()
}
func (f flag) kind() Kind {
return Kind((f >> flagKindShift) & flagKindMask)
}
同時(shí)獲取一種類型:(Type是一個(gè)接口,通常由 實(shí)現(xiàn)*rtype)
func (t *rtype) Kind() Kind { return Kind(t.kind & kindMask) }
因此,盡管他們似乎是在大多數(shù)的情況下平等,v.Kind()是不 v.Type().Kind()

TA貢獻(xiàn)1826條經(jīng)驗(yàn) 獲得超6個(gè)贊
文件reflect/value.go聲明reflect.Value
“重復(fù)typ.Kind() 除了方法值”的實(shí)現(xiàn)中的相關(guān)字段。所以,除非值是一個(gè)方法,value.Kind()
并且value.Type().Kind()
返回相同的數(shù)字。
- 2 回答
- 0 關(guān)注
- 454 瀏覽
添加回答
舉報(bào)