forked from cdarwin/go-koans
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathabout_pointers.go
More file actions
40 lines (31 loc) · 742 Bytes
/
about_pointers.go
File metadata and controls
40 lines (31 loc) · 742 Bytes
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
package go_koans
func aboutPointers() {
{
a := 3
b := a // 'b' is a copy of 'a' (all assignments are copy-operations)
b++
assert(a == 3) // variables are independent of one another
}
{
a := 3
b := &a // 'b' is the address of 'a'
*b = *b + 2 // de-referencing 'b' means acting like a mutable copy of 'a'
assert(a == 5) // pointers seem complicated at first but are actually simple
}
{
increment := func(i int) {
i++
}
a := 3
increment(a)
assert(a == 3) // variables are always passed by value, and so a copy is made
}
{
realIncrement := func(i *int) {
(*i)++
}
b := 3
realIncrement(&b)
assert(b == 4) // but passing a pointer allows others to mutate the value pointed to
}
}