forked from ardanlabs/gotraining
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example2.go
58 lines (44 loc) · 1.22 KB
/
example2.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
// All material is licensed under the Apache License Version 2.0, January 2004
// http://www.apache.org/licenses/LICENSE-2.0
// Sample program demonstrating that type assertions are a runtime and
// not compile time construct.
package main
import (
"fmt"
"math/rand"
"time"
)
// car represents something you drive.
type car struct{}
// String implements the fmt.Stringer interface.
func (car) String() string {
return "Vroom!"
}
// cloud represents somewhere you store information.
type cloud struct{}
// String implements the fmt.Stringer interface.
func (cloud) String() string {
return "Big Data!"
}
// =============================================================================
func main() {
// Seed the number random generator.
rand.Seed(time.Now().UnixNano())
// Create a slice of the Stringer interface values.
mvs := []fmt.Stringer{
car{},
cloud{},
}
// Let's run this experiment ten times.
for i := 0; i < 10; i++ {
// Choose a random number from 0 to 1.
rn := rand.Intn(2)
// Perform a type assertion that we have a concrete type
// of cloud in the interface value we randomly chose.
if v, ok := mvs[rn].(cloud); ok {
fmt.Println("Got Lucky:", v)
continue
}
fmt.Println("Got Unlucky")
}
}