funcmain() { list := make(List, 3) list[0] = 1//an int list[1] = "Hello"//a string list[2] = Person{"Dennis", 70}
for index, element := range list{ switch value := element.(type) { caseint: fmt.Printf("list[%d] is an int and its value is %d\n", index, value) casestring: 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) } } }
Comma-ok断言
Go语言里面有一个语法,可以直接判断是否是该类型的变量: value, ok = element.(T),这里value就是变量的值,ok是一个bool类型,element是interface变量,T是断言的类型。
funcmain() { list := make(List, 3) list[0] = 1// an int list[1] = "Hello"// a string list[2] = Person{"Dennis", 70}
for index, element := range list { if value, ok := element.(int); ok { fmt.Printf("list[%d] is an int and its value is %d\n", index, value) } elseif value, ok := element.(string); ok { fmt.Printf("list[%d] is a string and its value is %s\n", index, value) } elseif value, ok := element.(Person); ok { fmt.Printf("list[%d] is a Person and its value is %s\n", index, value) } else { fmt.Printf("list[%d] is of a different type\n", index) } } }
嵌入interface
就像我们在学习Struct时学习的匿名字段一样。组合的方式
源码包container/heap里面有这样的一个定义
type Interface interface { sort.Interface //嵌入字段sort.Interface Push(x interface{}) //a Push method to push elements into the heap Pop() interface{} //a Pop elements that pops elements from the heap }
type Interface interface { // Len is the number of elements in the collection. Len() int // Less returns whether the element with index i should sort // before the element with index j. Less(i, j int) bool // Swap swaps the elements with indexes i and j. Swap(i, j int) }