首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么地图类型的类型报告为53而不是21?

为什么地图类型的类型报告为53而不是21?
EN

Stack Overflow用户
提问于 2022-01-10 03:59:59
回答 1查看 108关注 0票数 0

显示代码:

代码语言:javascript
复制
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中找到

代码语言:javascript
复制
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)。为什么?

EN

回答 1

Stack Overflow用户

发布于 2022-01-10 05:31:45

如果您查看src/运行时/typekind.go kind.go,将有一个函数来检查该值是否直接存储在接口值中,这适用于您的情况,因为您正在创建t of interface{},但要将映射类型存储到它。

代码语言:javascript
复制
// 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)。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70647654

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档