如何反向知道interface变量里面实际保存了的是哪个类型的对象呢?目前常用的有两种方法:
1、value, ok = element.(T),这里value就是变量的值,ok是一个bool类型,element是interface变量,T是断言的类型。如果element里面确实存储了T类型的数值,那么ok返回true,否则返回false。
package main
import (
"fmt"
"strconv"
)
type List []Element
type Element interface{}
type Person struct {
name string
age int
}
func (p Person) String() string {
return "(name: " + p.name + " - " + strconv.Itoa(p.age) + "years old.)"
}
func main(){
List := make(List, 3)
List[0] = 1
List[1] = "Hello"
List[2] = Person{name: "Dannis", age:70}
for index, ele := range List {
if value, ok := ele.(int); ok {
fmt.Printf("List[%d] is an int, and its value is %d\n ", index, value )
}else if value, ok := ele.(string); ok {
fmt.Printf("List[%d] is a string and its value is %s\n ", index, value)
}else if value, ok := ele.(Person); ok {
fmt.Printf("List[%d] is a Person and its value is %s", index, value)
}else{
fmt.Printf("List[%d] is a of a different type", index)
}
}
}
// 输出结果:
List[0] is an int, and its value is 1
List[1] is a string and its value is Hello
List[2] is a Person and its value is (name: Dannis - 70years old.)
2、switch测试
package main
import (
"fmt"
"strconv"
)
type List []Element
type Element interface{}
type Person struct {
name string
age int
}
func (p Person) String() string {
return "(name: " + p.name + " - " + strconv.Itoa(p.age) + "years old.)"
}
func main(){
List := make(List, 3)
List[0] = 1
List[1] = "Hello"
List[2] = Person{name: "Dannis", age:70}
for index, element := range List {
switch value := element.(type) {
case int:
fmt.Printf("list[%d] is an int and its value is %d\n", index, value)
case string:
fmt.Printf("list[%d] is a string and its value is %s\n", index, value)
case Person:
fmt.Printf("list[%d] is a Person and its value is %s\n", index, value)
default:
fmt.Println("list[%d] is of a different type", index)
}
}list[0] is an int and its value is 1
list[1] is a string and its value is Hello
list[2] is a Person and its value is (name: Dannis - 70years old.)
}
//运行结果
list[0] is an int and its value is 1
list[1] is a string and its value is Hello
list[2] is a Person and its value is (name: Dannis - 70years old.)
这里有一点需要强调的是:element.(type)语法不能在switch外的任何逻辑里面使用,如果你要在switch外面判断一个类型就使用第一中判断方式。