forked from ardanlabs/gotraining
/
example5.go
57 lines (43 loc) · 1.29 KB
/
example5.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
// All material is licensed under the Apache License Version 2.0, January 2004
// http://www.apache.org/licenses/LICENSE-2.0
// Sample program to show how the concrete value assigned to
// the interface is what is stored inside the interface.
package main
import "fmt"
// printer displays information.
type printer interface {
print()
}
// user defines a user in the program.
type user struct {
name string
}
// print displays the user's name.
func (u user) print() {
fmt.Printf("User Name: %s\n", u.name)
}
func main() {
// Create values of type user and admin.
u := user{"Bill"}
// Add the values and pointers to the slice of
// printer interface values.
entities := []printer{
// Store a copy of the user value in the interface value.
u,
// Store a copy of the address of the user value in the interface value.
&u,
}
// Change the name field on the user value.
u.name = "Bill_CHG"
// Iterate over the slice of entities and call
// print against the copied interface value.
for _, e := range entities {
e.print()
}
// When we store a value, the interface value has its own
// copy of the value. Changes to the original value will
// not be seen.
// When we store a pointer, the interface value has its own
// copy of the address. Changes to the original value will
// be seen.
}