您的位置 首页 golang

学习Golang第19天 – 类型断言

类型断言(Type Assertion)是一个使用在接口值上的操作,用于检查接口类型变量所持有的值是否实现了期望的接口或者具体的类型。

在Go语言中类型断言的语法格式如下:

其中,x 表示一个接口的类型,T 表示一个具体的类型(也可为接口类型)。

该断言表达式会返回 x 的值(也就是 value)和一个布尔值(也就是 ok),可根据该布尔值判断 x 是否为 T 类型:

类型断言还可以配合 switch 使用,示例代码如下:

 package main
import (
    "fmt"
)
func main() {
    var a int
    a = 10
    getType(a)
}
func getType(a interface{}) {
    switch a.(type) {
    case int:
        fmt.Println("the type of a is int")
    case string:
        fmt.Println("the type of a is string")
    case float64:
        fmt.Println("the type of a is float")
    default:
        fmt.Println("unknown type")
    }
}  

运行结果如下:

the type of a is int

文章来源:智云一二三科技

文章标题:学习Golang第19天 – 类型断言

文章地址:https://www.zhihuclub.com/100875.shtml

关于作者: 智云科技

热门文章

网站地图