0
0
Goprogramming~5 mins

Common pointer use cases in Go

Choose your learning style9 modes available
Introduction

Pointers let you work with the exact place where data is stored. This helps you change data directly and use memory smartly.

When you want to change a variable inside a function and keep the change outside.
When you want to save memory by not copying large data structures.
When you want to share data between parts of your program safely.
When you need to work with linked data like linked lists or trees.
When you want to check if a variable has a value or is empty (nil).
Syntax
Go
var p *int       // p is a pointer to an int
p = &x           // p gets the address of x
fmt.Println(*p)   // prints the value at the address p points to

The * before a type means 'pointer to that type'.

The & operator gets the address of a variable.

Examples
Here, p points to x. Using *p gets the value of x.
Go
var x int = 10
var p *int = &x
fmt.Println(*p)  // prints 10
Passing a pointer to a function lets the function change the original variable.
Go
func changeValue(val *int) {
    *val = 20
}

func main() {
    x := 10
    changeValue(&x)
    fmt.Println(x)  // prints 20
}
You can check if a pointer is nil to see if it points to something or not.
Go
var p *int
if p == nil {
    fmt.Println("p is nil")
}
Sample Program

This program shows how passing a pointer to a function lets it change the original variable.

Go
package main

import "fmt"

func updateNumber(num *int) {
    *num = *num + 5
}

func main() {
    number := 10
    fmt.Println("Before:", number)
    updateNumber(&number)
    fmt.Println("After:", number)
}
OutputSuccess
Important Notes

Always be careful when using pointers to avoid changing data by mistake.

Using pointers can make your program faster by avoiding copying big data.

Nil pointers mean 'no value' or 'no address' and should be checked before use.

Summary

Pointers hold the address of variables, letting you access or change the original data.

Use pointers to modify variables inside functions or to save memory.

Always check for nil pointers to avoid errors.