-
Notifications
You must be signed in to change notification settings - Fork 0
/
interfaces-typeOf-variable.go
58 lines (50 loc) · 1.42 KB
/
interfaces-typeOf-variable.go
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
package main
import (
"fmt"
"strconv"
)
type Element interface{}
type List []Element
type Person struct {
name string
age int
}
func (p Person) String() string {
return "(name: " + p.name + " - age: " + strconv.Itoa(p.age) + " years)"
}
func main() {
list := make(List, 3)
list[0] = 1 // an int
list[1] = "Hello" // a string
list[2] = Person{"Dennis", 70}
/*
for index, element := range list {
if value, ok := element.(int); ok {
fmt.Printf("list[%d] is an int and its value is %d\n", index, value)
} else if value, ok := element.(string); ok {
fmt.Printf("list[%d] is a string and its value os %s\n", index, value)
} else if value, ok := element.(Person); ok {
fmt.Printf("list[%d] is a Person and its value is %s\n", index, value)
} else {
fmt.Printf("list[%d] is of a deifferent type\n")
}
}
*/
// We'd better use switch
for index, element := range list {
switch value := element.(type) {
case int:
fmt.Printf("list[%d] is an int and its value is %d\n", index, value)
case string:
fmt.Printf("list[%d] is an int and its value is %s\n", index, value)
case Person:
fmt.Printf("list[%d] is an int and its value is %s\n", index, value)
default:
fmt.Printf("list[%d] is of a different type\n", index)
}
}
}
/*
One thing to remember is that element.(type) cannot be used outside of the switch body,
which means in that case you have to use the comma-ok pattern .
*/