除 常量、别名类型 以及未命名类型 外,Go 强制要求使用显式类型转换。加上不支持操作符重载,所以我们总是能确定语句及表达式的明确含义。
a := 10
b := byte(a)
c := a + int(b) // 混合类型表达式必须确保类型一致
语法歧义
如果转换的目标是指针、单向通道或没有返回值的函数类型,那么必须使用括号,以避免造成语法分解错误。
x := 100
p := *int(&x) // cannot convert&x(type*int)to type int
// invalid indirect of int(&x) (type int)
println(p)
正确的做法是用括号,让编译器将 *int
解析为指针类型。
(*int)(p) // 如果没有括号:*(int(p))
(<-chan int)(c) // <-(chan int(c))
(func())(x) // func()x
func() int(x) // 有返回值的函数类型可省略括号,但依然建议使用。
(func() int)(x) // 使用括号后,更易阅读