You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
A pointer is a variable that stores the memory address of another variable. In Go, a pointer is represented using the `*` (asterisk) followed by the type of the stored value.
4
+
5
+
## Creating Pointers
6
+
7
+
You can create a pointer using the built-in `new` function:
8
+
9
+
```go
10
+
varp *int32 = new(int32) // p now stores a memory location
11
+
```
12
+
13
+
This creates a new `int32` value, sets it to zero (the zero value for integers), and returns a pointer to it.
14
+
15
+
## Using Pointers
16
+
17
+
You can change the value stored at the memory location a pointer points to:
18
+
19
+
```go
20
+
*p = 1// changes the value at the memory location p points to
21
+
```
22
+
23
+
You can also create a pointer from the address of another variable using the `&` operator:
24
+
25
+
```go
26
+
p = &i // p and i now reference the same int32 value in memory
27
+
```
28
+
29
+
## Pointers and Arrays
30
+
31
+
When working with arrays, you can pass a pointer to the array to a function if you want the function to be able to modify the original array:
32
+
33
+
```go
34
+
funcsquare(thing2 *[5]float64) [5]float64{
35
+
fori:=range thing2{
36
+
thing2[i] = thing2[i]*thing2[i]
37
+
}
38
+
return *thing2
39
+
}
40
+
```
41
+
42
+
In this function, `thing2` is a pointer to an array of `float64`. The function squares each element of the array. Because we're passing a pointer to the array, the original array is modified.
0 commit comments