Hi there!

In this programming, we will learn what is pointers in golang. We have already used them several times in previous posts. But let’s check them in more detail. Pointer is a parameter that stores the memory address and not the value itself.

Create Pointer

If we create one parameter and assign it to another, then golang makes a copy of it. And if we change the value of one parameter, the other will remain unchanged

package main

import "fmt"

func main() {
	var a int = 30
	var b int = a
	fmt.Println(a, b)
	b = 99
	fmt.Println(a, b)
}
$ go run main.go
30 30
30 99

But we can create a parameter that will be a pointer and will indicate the memory location in which the value of the first parameter is located, and then changing the value of any of them, both will be changed. Pointer is created as follows var VAR_NAME *TYPE

package main

import "fmt"

func main() {
	var a int = 30
	var b *int = &a
	fmt.Println(a, b)
	*b = 99
	fmt.Println(a, b)
}

When we specify a value for b, we specify not just the parameter a, but &a, which means that we specify a location in memory and not the value of the parameter. And when we are changing value of b we cannot simply specify b = VALUE, because b contain memory address and not value. To change value we need to add * before parameter name

$ go run main.go
30 0xc0000180c0
99 0xc0000180c0

As we can see from the output, changing the value of b also changed the value of a. But instead of b, we got not the value, but only the address in memory. To get the value of parameter b you need to use dereferencing.

Dereferencing

To get the value, just add * before the parameter name.

package main

import "fmt"

func main() {
	var a int = 30
	var b *int = &a
	fmt.Println(a, *b)
	*b = 99
	fmt.Println(a, *b)
}
$ go run main.go
30 30
99 99

Pointer default value

When we create a parameter that is a pointer but do not set its initial value, it will be nil

package main

import "fmt"

func main() {
	var b *int
	fmt.Println(b)
}
$ go run main.go
<nil>

Video