需要的知识 interface:https://blog.csdn.net/weixin_40165163/article/details/91905100
类型断言
x.(T)
检查x的动态类型是否是T,其中x必须是接口值。
直接使用:
func main() {
var x interface{}
x = 100
value1, ok := x.(int)
if ok {
//打印
fmt.Println(value1)
}
value2, ok := x.(string)
if ok {
//未打印
fmt.Println(value2)
}
}
需要注意如果不接收第二个参数也就是ok,这里失败的话则会直接panic,这里还存在一种情况就是x为nil同样会panic
func main() {
var x interface{}
x = "Hello"
value := x.(int)
fmt.Println(value)
}
输出:panic: interface conversion: interface {} is string, not int
输出:
100
若类型检查成功提取到的值也将拥有对应type的方法:
func main() {
var a interface{}
a = A{}
value := a.(A)
value.Hi()
fmt.Println(value.Name)
}
type A struct {
Name string
}
func (a A) String() string {
return "Type Is A"
}
func (a *A) Hi() {
fmt.Println(a)
}
switch使用:
package main
import "fmt"
func main() {
n := 100
JudgeType(n)
str := "Hello World"
JudgeType(str)
a := A{}
JudgeType(a)
a1 := new(A)
JudgeType(a1)
}
//这里需要注意case的顺序是有意义的因为可能存在一个值实现多个interface的情况
func JudgeType(a interface{}) {
switch value := a.(type) {
case nil:
fmt.Println("Type is nil")
case int:
fmt.Println("int:", value)
case string:
fmt.Println("string:", value)
case A:
fmt.Println("类型A:", value)
case *A:
fmt.Println("指针A", value)
default:
fmt.Println("未匹配")
}
}
type A struct {
}
func (a A) String() string {
return "Type Is A"
}
输出:
int: 100
string: Hello World
类型A: Type Is A
指针A Type Is A