1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
|
package main
import ( "fmt" "strconv" )
type Human struct { name string age int phone string }
type Element interface{}
type List []Element
type Person struct { name string age int }
func (h Human) String() string { return "<" + h.name + " - " + strconv.Itoa(h.age) + " years - phone: " + h.phone + ">" }
func (p Person) String() string { return "(name: " + p.name + " - age: " + strconv.Itoa(p.age) + " years)" }
func main() { Lucy := Human{"Lucy", 29, "10086"} fmt.Println("This human is:", Lucy)
list := make(List, 3) list[0] = 100 list[1] = "Hello Golang!" list[2] = Person{"Lily", 19}
for index, element := range list { if value, ok := element.(int); ok { fmt.Printf("list[%d] is an int and it's value is %d\n", index, value) } else if value, ok := element.(string); ok { fmt.Printf("list[%d] is a string and it's value is %s\n", index, value) } else if value, ok := element.(Person); ok { fmt.Printf("list[%d] is a Person and it's value is %s\n", index, value) } else { fmt.Printf("list[%d] is a different type\n", index) } }
for index, element := range list { switch value := element.(type) { case int: fmt.Printf("list[%d] is an int, it's value is %d\n", index, value) case string: fmt.Printf("list[%d] is a string, it's value is %s\n", index, value) case Person: fmt.Printf("list[%d] is a Person, it's value is %s\n", index, value) default: fmt.Printf("list[%d] is a differernt type", index) } } }
|