新入门的疑惑, 为什么 反射 reflect.Kind(1) 返回的 是 bool? 有没有大佬解释一下

Cianyi · · 1263 次点击
没啥特殊的,源码就是这么定义的. `reflect.Kind(1)` 等于 `Bool`,`fmt` 包默认打印 `String() string` 的值, ```go // A Kind represents the specific kind of type that a Type represents. // The zero Kind is not a valid kind. type Kind uint const ( Invalid Kind = iota // 0 Bool // 1 Int // 2 ... ) // String returns the name of k. func (k Kind) String() string { if int(k) < len(kindNames) { return kindNames[k] } return "kind" + strconv.Itoa(int(k)) } var kindNames = []string{ Invalid: "invalid", Bool: "bool", Int: "int", ... } ```
#1
更多评论
1楼 <a href="/user/GGXXLL" title="@GGXXLL">@GGXXLL</a> 很赞,重点就在func (k Kind) String()。当楼主使用reflect.Kind(1) ,把1的类型转换成Kind时,1的含义就变了,它的内在含义就从“整形数字”,变成了“某种类型”。fmt.Println等打印函数的内部,会判断打印的对象有没有实现String方法,而这里的Kind类型有实现,就把&#34;invalid&#34;、&#34;bool&#34;这样的字符串返回了。
#2