类型断言

类型断言

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

第一种:

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 Point struct {
    x int
    y int
}
 
func main() {
    var a interface{}go
    var p = Point{1, 2}
    a = p
    b, ok := a.(int) // 肯定转换失败的
    if ok{
        fmt.Println("转换成功")
    } else {
        fmt.Println("转换失败") // 转换失败
    }
    fmt.Println(b) // 0
}

Type Switch

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

package main

import "fmt"

func findType(i interface{}) {
    switch x := i.(type) {
    case int:
        fmt.Println(x, "is int")
    case string:
        fmt.Println(x, "is string")
    case nil:
        fmt.Println(x, "is nil")
    default:
        fmt.Println(x, "not type matched")
    }
}

func main() {
    findType(10)      // int
    findType("hello") // string

    var k interface{} // nil
    findType(k)

    findType(10.23) //float64
}

输出如下:

10 is int
hello is string
<nil> is nil
10.23 not type matched

额外说明一下:

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

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

Last updated

Was this helpful?