ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
### ok-pattern ``` if t, ok := X.(T); ok == true { // 接口变量是该类型时处理 } ``` ``` package main import "fmt" // 创建一个结构体 type Datalist struct { Name string Age int } func main() { // 切片 s := make([]interface{}, 3) s[0] = 1 s[1] = "abc" s[2] = Datalist{"Pony", 20} //结构体 // 遍历 for index, data := range s { if t, ok := data.(int); ok == true { fmt.Printf("s[%d] Type = int, Value = %d\n", index, t) } if t, ok := data.(string); ok == true { fmt.Printf("s[%d] Type = string, Value = %s\n", index, t) } if t, ok := data.(Datalist); ok == true { fmt.Printf("s[%d] Type = Datalist, Datalist.Name = %v, Datalist.Age = %d\n", index, t.Name, t.Age) } } } 结果: s[0] Type = int, Value = 1 s[1] Type = string, Value = abc s[2] Type = Datalist, Datalist.Name = Pony, Datalist.Age = 20 ``` ### switch-type ``` switch t := X.(T){ case 类型1: //接口类型是类型1时处理 case 类型2 : // 接口类型是类型2时处理 ... default: //当类型不是case中所列举的类型时处理 } ``` ``` package main import "fmt" // 创建一个结构体 type Datalist struct { Name string Age int } func main() { // 切片 s := make([]interface{}, 3) s[0] = 1 s[1] = "abc" s[2] = Datalist{"Pony", 20} //结构体 // 遍历 for index, data := range s { switch t := data.(type) { case int: fmt.Printf("s[%d] Type = int, Value = %d\n", index, t) case string: fmt.Printf("s[%d] Type = string, Value = %s\n", index, t) case Datalist: fmt.Printf("s[%d] Type = Datalist, Datalist.Name = %v, Datalist.Age = %d\n", index, t.Name, t.Age) } } } 结果: s[0] Type = int, Value = 1 s[1] Type = string, Value = abc s[2] Type = Datalist, Datalist.Name = Pony, Datalist.Age = 20 ```