golang中的类型断言只能对于接口类型变量,其它类型变量的类型是确定的,否则编译器会报错

    1. v := varI.(T)

    标准类型断言:

    1. if v, ok := varI.(T); ok {
    2. //dosoming(v)
    3. }
    4. //varI is not of type T
    5. if _, ok := varI.(T); ok {
    6. //todo
    7. }

    example:

    1. package main
    2. import (
    3. "fmt"
    4. "math"
    5. )
    6. type Square struct {
    7. side float32
    8. }
    9. type Circle struct {
    10. radius float32
    11. }
    12. type Shaper interface {
    13. Area() float32
    14. }
    15. func main() {
    16. var areaIntf Shaper
    17. sq1 := new(Square)
    18. sq1.side = 5
    19. areaIntf = sq1
    20. // Is Square the type of areaIntf?
    21. if t, ok := areaIntf.(*Square); ok {
    22. fmt.Printf("The type of areaIntf is: %T\n", t)
    23. }
    24. if u, ok := areaIntf.(*Circle); ok {
    25. fmt.Printf("The type of areaIntf is: %T\n", u)
    26. } else {
    27. fmt.Println("areaIntf does not contain a variable of type Circle")
    28. }
    29. }
    30. func (sq *Square) Area() float32 {
    31. return sq.side * sq.side
    32. }
    33. func (ci *Circle) Area() float32 {
    34. return ci.radius * ci.radius * math.Pi
    35. }

    备注
    如果忽略 areaIntf.(*Square) 中的 * 号,会导致编译错误:impossible type assertion: Square does not implement Shaper (Area method has pointer receiver)