显示代码:
package main
import (
"fmt"
"unsafe"
)
// copy form src/runtime/type.go
type _type struct {
size uintptr
ptrdata uintptr // size of memory prefix holding all pointers
hash uint32
tflag tflag
align uint8
fieldAlign uint8
kind uint8
equal func(unsafe.Pointer, unsafe.Pointer) bool
gcdata *byte
str nameOff
ptrToThis typeOff
}
type tflag uint8
type nameOff int32
type typeOff int32
// copy form src/runtime/runtime2.go
type eface struct {
_type *maptype
data unsafe.Pointer
}
// copy form src/runtime/type.go
type maptype struct {
typ _type
key *_type
elem *_type
bucket *_type // internal type representing a hash bucket
// function for hashing keys (ptr to key, seed) -> hash
hasher func(unsafe.Pointer, uintptr) uintptr
keysize uint8 // size of key slot
elemsize uint8 // size of elem slot
bucketsize uint16 // size of bucket
flags uint32
}
func main() {
var t interface{} = map[int]int{1: 1}
p := (*eface)(unsafe.Pointer(&t))
fmt.Println(p._type.typ.kind) // 53
}打印53,
但您可以在src/运行时/ find kind.go中找到
const (
kindBool = 1 + iota
kindInt
kindInt8
kindInt16
kindInt32
kindInt64
kindUint
kindUint8
kindUint16
kindUint32
kindUint64
kindUintptr
kindFloat32
kindFloat64
kindComplex64
kindComplex128
kindArray
kindChan
kindFunc
kindInterface
kindMap // 21
kindPtr
kindSlice
kindString
kindStruct
kindUnsafePointer
kindDirectIface = 1 << 5
kindGCProg = 1 << 6
kindMask = (1 << 5) - 1
)地图类型为const 21。同样,chan是50岁,而不是kindChan(18)。为什么?
发布于 2022-01-10 05:31:45
如果您查看src/运行时/typekind.go kind.go,将有一个函数来检查该值是否直接存储在接口值中,这适用于您的情况,因为您正在创建t of interface{},但要将映射类型存储到它。
// isDirectIface reports whether t is stored directly in an interface value.
func isDirectIface(t *_type) bool {
return t.kind&kindDirectIface != 0
}当使用p作为isDirectIface(&p._type.typ)的值时,它返回true,因为设置了与接口类型相对应的底层位值(kindDirectIface = 1 << 5,32)。
因此,实际上,该值53表示(十进制21+32)作为接口类型32 (kindDirectIface)存储的映射类型21 (kindMap)。
https://stackoverflow.com/questions/70647654
复制相似问题