forked from ardanlabs/gotraining
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample3.go
50 lines (39 loc) · 1.27 KB
/
example3.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
// 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 the basic concept of using a pointer
// to share data.
package main
import "fmt"
// user represents a user in the system.
type user struct {
name string
email string
logins int
}
func main() {
// Declare and initialize a variable named bill of type user.
bill := user{
name: "Bill",
email: "[email protected]",
}
//** We don't need to include all the fields when specifying field
// names with a struct literal.
// Pass the "address of" the bill value.
display(&bill)
// Pass the "address of" the logins field from within the bill value.
increment(&bill.logins)
// Pass the "address of" the bill value.
display(&bill)
}
// increment declares logins as a pointer variable whose value is
// always an address and points to values of type int.
func increment(logins *int) {
*logins++
fmt.Printf("&logins[%p] logins[%p] *logins[%d]\n\n", &logins, logins, *logins)
}
// display declares u as user pointer variable whose value is always an address
// and points to values of type user.
func display(u *user) {
fmt.Printf("%p\t%+v\n", u, *u)
fmt.Printf("Name: %q Email: %q Logins: %d\n\n", u.name, u.email, u.logins)
}