golang中的类型断言只能对于接口类型变量,其它类型变量的类型是确定的,否则编译器会报错
v := varI.(T)
标准类型断言:
if v, ok := varI.(T); ok {
//dosoming(v)
}
//varI is not of type T
if _, ok := varI.(T); ok {
//todo
}
example:
package main
import (
"fmt"
"math"
)
type Square struct {
side float32
}
type Circle struct {
radius float32
}
type Shaper interface {
Area() float32
}
func main() {
var areaIntf Shaper
sq1 := new(Square)
sq1.side = 5
areaIntf = sq1
// Is Square the type of areaIntf?
if t, ok := areaIntf.(*Square); ok {
fmt.Printf("The type of areaIntf is: %T\n", t)
}
if u, ok := areaIntf.(*Circle); ok {
fmt.Printf("The type of areaIntf is: %T\n", u)
} else {
fmt.Println("areaIntf does not contain a variable of type Circle")
}
}
func (sq *Square) Area() float32 {
return sq.side * sq.side
}
func (ci *Circle) Area() float32 {
return ci.radius * ci.radius * math.Pi
}
备注
如果忽略 areaIntf.(*Square)
中的 *
号,会导致编译错误:impossible type assertion: Square does not implement Shaper (Area method has pointer receiver)
。