Go-Programming-I-Pointers-in-Golang

Bond。James Bond。

A pointer is a special type that is used to reference a value. Understanding it better can help you write advanced code in Go.

Variables

Computer memory can be thought of as a sequence of boxes, placed one after another in a line. Each box is labeled with a unique number, which increments sequentially. The unique location number is called a memory address.

A variable is just a convenient, alphanumeric nickname for a piece of memory location assigned by the compiler. When you declare variables, you are given a memory location to use from the free memory available.

Pointers

A pointer value is the address of a variable. A pointer is thus the location at which a value is stored. With a pointer, we can read or update the value of a variable indirectly, without using or even knowing the variable’s name, if indeed it has a name.

In the following example,

  • The statement &x yields a pointer to an integer variable.
  • y := &x We say y points to x, or y contains the address of x.
  • The expression *y yields the value of that integer variable, which is 9 here.

Why is pointer useful?

“Pointers are used for efficiency because everything in Go is passed by value so they let us pass an address where data is held instead of passing the data’s value, to avoid unintentionally changing data, and so we can access an actual value in another function and not just a copy of it when we want to mutate it.”

Pointers Example

A copy of the value is sent to a function as an argument in pass-by-value. Any changes in the function will only impact the function’s variable; it will not update the original value outside of the function scope.

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
package main

import "fmt"

type User struct {
Name string
Age int
}

func (u User) String() string {
return fmt.Sprintf("User[Name: %s, Age: %d]", u.Name, u.Age)
}

// value receiver
func (u User) SetAge(age int) {
u.Age = age
fmt.Println(u)
}

func main() {
u := User{
Name: "John",
Age: 25,
}
u.SetAge(30)
fmt.Println(u)
}

Result:

1
2
User[Name: John, Age: 30]
User[Name: John, Age: 25]

Pass by pointer

In Go, everything is passed-by-value. We use pointers when we want to pass by reference and set the original value.

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
package main

import "fmt"

type User struct {
Name string
Age int
}

func (u User) String() string {
return fmt.Sprintf("User[Name: %s, Age: %d]", u.Name, u.Age)
}

// value receiver
func (u *User) SetAge(age int) {
u.Age = age
fmt.Println(u)
}

func main() {
u := User{
Name: "John",
Age: 25,
}
u.SetAge(30)
fmt.Println(u)
}

Result:

1
2
User[Name: John, Age: 30]
User[Name: John, Age: 30]