【发布时间】:2021-04-26 20:11:42
【问题描述】:
这个例子展示了 int 类型可以转换为 string 类型。但我的问题是为什么?
package main
import (
"fmt"
"reflect"
)
func main() {
it := reflect.TypeOf(42)
st := reflect.TypeOf("hello")
fmt.Printf("%q is convertible to %q: %v\n",
it, st, it.ConvertibleTo(st))
// OUTPUT: "int" is convertible to "string": true
fmt.Printf("%q is convertible to %q: %v\n",
st, it, st.ConvertibleTo(it))
// OUTPUT: "string" is convertible to "int": false
}
如果我错了,请纠正我。但是这不应该是false吗?
reflect.TypeOf(int(0)).ConvertibleTo(reflect.TypeOf("string"))
【问题讨论】:
-
正如@Hymns 所指出的,
int到string的转换是一种原始转换——可能不是你所期望的。如果您想要特定int的string表示 - 使用strconv.Itoa(x)或fmt.Sprint(x) -
作为记录,有一个 active proposal 不允许这样做,因为此转换的潜在奇怪/令人困惑的行为