-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpointers.go
More file actions
41 lines (37 loc) · 1.04 KB
/
Copy pathpointers.go
File metadata and controls
41 lines (37 loc) · 1.04 KB
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
package main
import (
"fmt"
)
/*
We’ll show how pointers work in contrast to values with 2 functions:
zeroval and zeroptr. zeroval has an int parameter, so arguments will
be passed to it by value. zeroval will get a copy of ival distinct
from the one in the calling function.
*/
func zeroval(ival int) {
ival = 0
}
/*
zeroptr in contrast has an *int parameter,
meaning that it takes an int pointer.
The *iptr code in the function body then dereferences the pointer
from its memory address to the current value at that address.
Assigning a value to a dereferenced pointer changes the value at
the referenced address.
*/
func zeroptr(iptr *int) {
*iptr = 0
}
func main() {
i := 1
fmt.Println("initial:", i)
zeroval(i)
fmt.Println("zeroval:", i)
//The &i syntax gives the memory address of i, i.e. a pointer to i.
zeroptr(&i)
fmt.Println("zeroptr:", i)
//Pointers can be printed too.
fmt.Println("pointer:", &i)
//zeroval doesn’t change the i in main, but zeroptr does
//because it has a reference to the memory address for that variable.
}