Go 语言 中的 类型断言 也支持 switch 语句来判断断言的结果,同时,如果 接口 的值为 nil,那么会永远断言失败。
如果接口值为 nil,永远断言失败
package main
import (
"fmt"
)
func main() {
fmt.Println("嗨客网(www.haicoder.net)")
// 如果接口值为 nil,永远断言失败
var intvalue interface{}
if value, ok := intvalue.(int); ok{
fmt.Println("Ok Value =", value, "Ok =", ok)
}else{
fmt.Println("Failed Value =", value, "Ok =", ok)
}
}
程序运行后,控制台输出如下:
首先,我们定义了一个接口 类型 的 变量 intvalue,并且,没有给 intvalue 赋值,所以 intvalue 为 nil,接着,我们使用类型断言将 intvalue 转成 int 类型。
最后,我们发现,类型断言失败,变量的值为 0,表示成功的结果为 false。
类型断言的判断,支持 switch 语句
package main
import (
"fmt"
)
func main() {
fmt.Println("嗨客网(www.haicoder.net)")
// 类型断言的判断,支持 switch 语句
var intvalue interface{}
intvalue = 99.8
switch intvalue.(type) {
case int:
fmt.Println("Type Int")
case float32:
fmt.Println("Type Float32")
case float64:
fmt.Println("Type Float64")
case string:
fmt.Println("Type string")
}
}
程序运行后,控制台输出如下:
首先,我们定义了一个接口类型的变量 intvalue,并且,给其赋值为一个 float64 类型的值。接着,我们使用接口类型 .(type)
来判断接口的类型。
在 switch 语句里面判断接口的类型,是否为 int、float32、float64 和 string 类型,并且打印最后匹配成功后的类型。
因为,我们定义的接口的类型为 float64 类型,因此最后匹配成功了 float64 的 case 语句。
类型断言的判断,支持 switch 语句
package main
import (
"fmt"
)
func main() {
fmt.Println("嗨客网(www.haicoder.net)")
// 类型断言的判断,支持 switch 语句
var intvalue interface{}
intvalue = 99.8
switch intvalue.(type) {
case int:
fmt.Println("Type Int, Value =", intvalue.(int))
case float32:
fmt.Println("Type Float32, Value =", intvalue.(float32))
case float64:
fmt.Println("Type Float64, Value =", intvalue.(float64))
case string:
fmt.Println("Type string, Value =", intvalue.(string))
}
}
程序运行后,控制台输出如下:
我们在类型断言使用 switch 语句判断类型时,同时,可以获取转成成功后的变量的值。
Go 语言中的类型断言也支持 switch 语句来判断断言的结果,同时,如果接口的值为 nil,那么会永远断言失败。