1、通過switch實現類型斷言
示例:
package main
import "fmt"
type Student struct {
name string
id int
}
func main() {
i := make([]interface{}, 3)
i[0] = 1 //int
i[1] = "hello go" //string
i[2] = Student{"mike", 666} //Student
//類型查詢,類型斷言
for index, data := range i {
switch value := data.(type) {
case int:
fmt.Printf("x[%d] 類型為int, 內容為%d\n", index, value)
case string:
fmt.Printf("x[%d] 類型為string, 內容為%s\n", index, value)
case Student:
fmt.Printf("x[%d] 類型為Student, 內容為name = %s, id = %d\n", index, value.name, value.id)
}
}
}
執行結果:
x[0] 類型為int, 內容為1 x[1] 類型為string, 內容為hello go x[2] 類型為Student, 內容為name = mike, id = 666
