package main
import (
"fmt"
. "strconv"
)
type Element interface{}
type List []Element
type Person struct {
name string
age int
}
func (P Person) String() string {
return "My name is " + P.name + " my age is " + Itoa(P.age)
}
var slice_1 = []string{"hello"}
var map_1 = map[string]string{"city": "beijing", "name": "cs", "from": "usa"}
func main() {
list := make(List, 5)
list[0] = 1 // an int
list[1] = "Hello" // a string
list[2] = Person{"barry", 100} // struct
list[3] = slice_1 // a slice
list[4] = map_1 // a map
for _, element := range list {
switch v:=element.(type) { //v是具体的值对象了,而element还是interface对象
case int:
fmt.Println(element, ",int")
case string:
fmt.Println(element, ",string")
case Person:
fmt.Println(element, ",Person struct")
default:
fmt.Println(element, ",others like slice,map...")
}
}
}
一般切片只能存放一种数据类型,但是有了interface可以高度抽象,让切片存放的数据类型任意!
下面是例子。