go 类型转换
Go Conversions 和 类型断言是两种类型转换方式。
1 Go Conversions
*Point(p) // same as *(Point(p))
(*Point)(p) // p is converted to *Point
<-chan int(c) // same as <-(chan int(c))
(<-chan int)(c) // c is converted to <-chan int
func()(x) // function signature func() x
(func())(x) // x is converted to func()
(func() int)(x) // x is converted to func() int
func() int(x) // x is converted to func() int (unambiguous)
1 类型断言
type (
Bar interface {
Bar()
}
Foobar interface {
Bar()
Foo()
}
fbStr string
)
func (fbStr)Foo() {}
func (fbStr)Bar() {}
func main() {
var test fbStr = "test"
var a Bar = test //这里可以隐式转换
var b Foobar
b = a.(Foobar) //这里不是子集,变量需要断言,也可以 b = a.(fbStr)
var a2 Foobar = test
var b2 Bar
b2 = a2 //这里 Bar 是 Foobar 的子集,不需要断言
fmt.Println(b, b2)
}
编译时会检查当前变量所属类型的方法,如果是子集或相同就可以隐式转换
运行时会检查当前变量的方法,如果是子集或相同就可以断言转换
总结:可以用类型判断转换的,就可以隐式转换;只能用变量判断转换的,就不可以隐式转换。
断言还可以断言空方法的接口(比如 interface{})为简单类型,或者直接用类型转换实现而不用断言
var kn interface{} = "test"
tkn := kn.(string)
fmt.Println(tkn)