-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathpointers.go
90 lines (56 loc) · 2 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
80
81
82
83
84
85
86
87
88
89
90
package main
import (
"fmt"
"github.com/benhalstead/gotraining/tutorial"
)
func main() {
// In Go, when you pass a variable to a function (with the exception of maps, slices and channels), the function will receive
// a COPY of that variable - if you change it inside the function, the original value is unaffected.
// This mechanism is known in most programming languages as call by value
tutorial.Section("Call by value")
a := 2
increment(a)
fmt.Printf("a is still %d\n", a)
tutorial.Section("Call by value - exception for maps")
m := map[string]int{
"ORIGINAL": 0,
}
fmt.Printf("Before: %v\n", m)
addToMap(m)
fmt.Printf("After: %v\n", m)
tutorial.Section("Pointers")
// If we want a function to be able to modify (mutate) the passed variable, we need to pass a pointer to that variable
// Formally a pointer is the address in memory of a value
// We can obtain a pointer to any value using the ampersand symbol
ap := &a
// Conveniently (but sometimes confusingly) man
fmt.Printf("ap has value %v and is type %T\n", ap, ap)
tutorial.Section("Pointer types")
// Pointers are typed. A pointer to an int is considered a different type from a pointer to a string
s := "Test string"
sp := &s
fmt.Printf("ap is type %T and sp is type %T\n", ap, sp)
tutorial.Section("Dereferencing")
// You use the * symbol to get the underlying value from a pointer - this action is known as dereferencing
var x int
x = *ap
fmt.Printf("x has value %d and is type %T\n", x, x)
// Note that dereferencing a pointer while assigning it to a variable gets you a COPY of the value it points to. In this example,
// if we change the value of x, we're not changing the value of a
x = 3
fmt.Printf("a is still: %d, but x is now: %d\n", a, x)
tutorial.Section("Call by reference")
incrementRef(&a)
fmt.Printf("a is now %d\n", a)
incrementRef(&a)
fmt.Printf("a is now %d\n", a)
}
func increment(i int) {
i++
}
func incrementRef(i *int) {
*i++
}
func addToMap(m map[string]int) {
m["NEW"] = 1
}