interface{} 的行为方式有一个例外,@Jeremy Wall 已经给出了指针。如果传递的数据最初被定义为 []interface{}。
package main
import (
"fmt"
)
type interfaceSliceType []interface{}
var interfaceAsSlice interfaceSliceType
func main() {
loop(append(interfaceAsSlice, 1, 2, 3))
loop(append(interfaceAsSlice, "1", "2", "3"))
// or
loop([]interface{}{[]string{"1"}, []string{"2"}, []string{"3"}})
fmt.Println("------------------")
// and of course one such slice can hold any type
loop(interfaceSliceType{"string", 999, map[int]string{3: "three"}})
}
func loop(slice []interface{}) {
for _, elem := range slice {
switch elemTyped := elem.(type) {
case int:
fmt.Println("int:", elemTyped)
case string:
fmt.Println("string:", elemTyped)
case []string:
fmt.Println("[]string:", elemTyped)
case interface{}:
fmt.Println("map:", elemTyped)
}
}
}
输出:
int: 1
int: 2
int: 3
string: 1
string: 2
string: 3
[]string: [1]
[]string: [2]
[]string: [3]
------------------
string: string
int: 999
map: map[3:three]
试试看