/
pointers.go
79 lines (63 loc) · 2.07 KB
/
pointers.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package main
// user represents an user in the system.
type user struct {
name string
email string
}
func main() {
// -------------
// Pass by value
// -------------
// Declare variable of type int with a value of 10.
// This value is put on a stack with a value of 10.
count := 10
// To get the address of a value, we use &.
println("count:\tValue Of[", count, "], \tAddr Of[", &count, "]")
// Pass the "value of" count.
increment1(count)
// Printing out the result of count. Nothing has changed.
println("count:\tValue Of[", count, "], \tAddr Of[", &count, "]")
// Pass the "address of" count.
// This is still considered pass by value, not by reference because the address itself is a value.
increment2(&count)
// Printing out the result of count. count is updated.
println("count:\tValue Of[", count, "], \tAddr Of[", &count, "]")
// ---------------
// Escape analysis
// ---------------
stayOnStack()
escapeToHeap()
}
func increment1(inc int) {
// Increment the "value of" inc.
inc++
println("inc1:\tValue Of[", inc, "], \tAddr Of[", &inc, "]")
}
// increment2 declares count as a pointer variable whose value is always an address and points to
// values of type int.
// The * here is not an operator. It is part of the type name.
// Every type that is declared, whether you declare or it is predeclared, you get for free a pointer.
func increment2(inc *int) {
// Increment the "value of" count that the "pointer points to".
// The * is an operator. It tells us the value of the pointer points to.
*inc++
println("inc2:\tValue Of[", inc, "], \t Value Points To[", *inc, "], \t Addr Of [", &inc, "]")
}
// stayOnStack shows how the variable does not escape.
func stayOnStack() user {
// In the stayOnStack stack frame, create a value and initialize it.
u := user{
name: "Hoanh An",
email: "hoanhan@bennington.edu",
}
// Take the value and return it, pass back up to main stack frame.
return u
}
// escapeToHeap shows how the variable escape.
func escapeToHeap() *user {
u := user{
name: "Hoanh An",
email: "hoanhan@bennington.edu",
}
return &u
}