package main
import (
"fmt"
)
//类型断言1
//str,ok := a.(string)
//类型断言 返回值及是否成功
func assign(a interface{}) {
fmt.Printf("%T \n", a)
str, ok := a.(string)
if !ok {
fmt.Println("猜错了")
} else {
fmt.Println("传进来的是个字符串:", str)
}
}
//类型断言2
// a.(type) 获取值的类型
func assign2(a interface{}) {
fmt.Printf("%T \n", a)
switch a.(type) {
case string:
fmt.Println("是字符串:", a.(string))
case int:
fmt.Println("是int:", a.(int))
case bool:
fmt.Println("是bool:", a.(bool))
default:
fmt.Printf("未知类型:%T", a)
}
}
func main() {
assign(100)//猜错了
assign2(100)//是int: 100
}
Golang 类型断言
最新推荐文章于 2025-05-18 16:57:33 发布