dongqiao9394 2013-12-13 16:53
浏览 392
已采纳

在go Reflection包中,调用Value.Kind()是Value.Type()。Kind()的语法糖吗?

Both of the reflect.Type interface and reflect.Value type implement the same Kind() method signature, suppose that we have some value object v := reflect.ValueOf(x)

Is v.Kind() just call v.Type().Kind() ?

  • 写回答

2条回答 默认 最新

  • dongliao4353 2013-12-13 17:13
    关注

    They contain the same value, but do not seem to refer to the same thing:

    A Type is usually implemented by unexported struct rtype (via TypeOf), while the Value contains a *rtype and extends flag, which is itself a reduced form of the 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.
    

    When getting the ValueOf something:

    // 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}
    }
    

    And so when you get the kind of a Value (remember it extends its flag):

    func (v Value) Kind() Kind {
        return v.kind()
    }
    
    func (f flag) kind() Kind {
        return Kind((f >> flagKindShift) & flagKindMask)
    }
    

    While getting the kind of a type: (Type is an interface, usually implemented by *rtype)

    func (t *rtype) Kind() Kind { return Kind(t.kind & kindMask) }
    

    So although they seem to be equal in most of the cases, v.Kind() is not v.Type().Kind()

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题