/*
comma-ok断言:
Go语言里面有一个语法,可以直接判断是否是该类型的变量:
value, ok = element.(T),
这里value就是变量的值,ok是一个bool类型,element是interface变量,
T是断言的类型
*/
package main
import "fmt"
type Elementer interface{}
type Person struct {
name string
age int
}
func main() {
var list []Elementer = make([]Elementer, 3) //空接口类型
list[0] = 1
list[1] = "ads"
list[2] = Person{"mike", 12}
for index, element := range list {
if value, ok := element.(int); ok == true {
fmt.Printf("list[%d] is an int and its value is %d
", index, value)
} else if value, ok := element.(string); ok == true {
fmt.Printf("list[%d] is an int and its value is %s
", index, value)
} else if value, ok := element.(Person); ok == true {
fmt.Printf("list[%d] is an int and its value is [%s,%d]
", index, value.name, value.age)
}
}
}