类型断言

类型断言

由于接口是一般类型,不知道具体类型,如果要转成具体类型,就需要使用类型断言。 具体的使用方式有两种:

第一种:

t := i.(T)

第二种

t, ok:= i.(T)

不带检测的类型断言

代码示例:

type Point struct {
    x int
    y int
}
 
func main() {
    var a interface{}
    var p = Point{1, 2}
    a = p // 这是可以的
    var b Point
    //b = a // 这时不可以的,要使用断言,如下
    b = a.(Point) // 这就是类型断言,表示看看能不能将 a 转换成 Point,再赋给 b
    c := a.(Point)
    fmt.Println(b) // {1 2}
    fmt.Printf("c的类型=%T,值=%v", c, c) // c的类型=main.Point,值={1 2}
}

带检测的类型断言

在进行类型断言时,如果类型不匹配,就会报 panic,导致程序终止 因此在进行类型断言时,需要检测机制,如果成功就继续执行,否则不要报 panic

代码示例

Type Switch

如果需要区分多种类型,可以使用 type switch 断言

输出如下:

额外说明一下:

  • 如果值是 nil,那么匹配的是case nil

  • 如果你的值在 switch-case 里并没有匹配对应的类型,那么走的是 default 分

Last updated