funcmain() { list := List{} list = append(list, 123) list = append(list, "hello dottie") list = append(list, Person{"china", 100}) list = append(list, &list[2])
// 转换类型,返回值有两个(value, isSuccess) // 如果转换成功的话, ok为true,person就是Person类型的对象, // 转换失败的话,ok为false, person为nil person, ok := (list[2]).(Person) if ok { fmt.Println("*****************") fmt.Println(person.String()) fmt.Println(person, person.name, ok) fmt.Println("*****************") }
for index, value := range list { // 1. value.(type)只能在switch中使用 // 2. value.(type)的返回值将value转化成实际类型的值 switch v := value.(type) { caseint: fmt.Printf("list[%d] is an int and its value is %d\n", index, v) casestring: fmt.Printf("list[%d] is an string and its value is %s\n", index, v) case Person: fmt.Println(v) fmt.Printf("list[%d] is an Person and its value is %s\n", index, v.String()) default: fmt.Printf("list[%d] is of a different type %v\n", index, v) } } }