函数使用 interface{}
作为参数时,可以接收各种类型的数据。使用的时候通常需要判断具体是哪一种类型,并且将 interface{}
转成这个类型,这时候就需要类型断言。
语法
具体类型匹配
x.(string)
x.(int)
x.(bool)
x.(int32)
switch case 中匹配
switch i.(type) {
case string:
fmt.Println("is string")
case int:
fmt.Println("is int")
}
示例
基本类型
package main
import "fmt"
func f(i interface{}) {
v, ok := i.(string)
if ok {
fmt.Println("ok, string is:", v)
}
switch i.(type) {
case string:
fmt.Println(i, "is string")
case int:
fmt.Println(i, "is int")
}
}
func main() {
i := "hefs"
f(i)
a := 33
f(a)
}
结构体类型
package main
import "fmt"
type People struct {
Name string
Age int
No int
}
type Student struct {
SNo int
People
}
func main() {
s := Student{1, People{"kika", 33, 1}}
f(s)
p := People{"lisi", 22, 123}
f(p)
}
func f(i interface{}) {
v, ok := i.(Student)
if ok {
// fmt.Printf("SNo is: %v\n", i.SNo)
fmt.Printf("SNo is: %v\n", v.SNo)
fmt.Printf("%#v is Student, after convert is: \n%#v\n", i, v)
}
v2, ok2 := i.(People)
if ok2 {
// fmt.Printf("SNo is: %v\n", i.No)
fmt.Printf("SNo is: %v\n", v2.No)
fmt.Printf("%#v is People, after convert is: \n%#v\n", i, v2)
}
}
输出:
SNo is: 1
main.Student{SNo:1, People:main.People{Name:"kika", Age:33, No:1}} is Student, after convert is:
main.Student{SNo:1, People:main.People{Name:"kika", Age:33, No:1}}
SNo is: 123
main.People{Name:"lisi", Age:22, No:123} is People, after convert is:
main.People{Name:"lisi", Age:22, No:123}