0
0
Goprogramming~5 mins

Why pointers are needed in Go

Choose your learning style9 modes available
Introduction

Pointers let you directly access and change the place where data is stored. This helps save memory and lets functions change values outside their own space.

When you want a function to change the original value of a variable.
When you want to save memory by not copying large data structures.
When you need to share data between parts of a program without making copies.
When working with data structures like linked lists or trees that need references to other parts.
When you want to improve performance by avoiding copying big amounts of data.
Syntax
Go
var p *int  // p is a pointer to an int
p = &x      // p gets the address of variable x
fmt.Println(*p) // prints the value at the address p points to

The & operator gets the address of a variable.

The * operator accesses the value at the pointer's address.

Examples
Here, p points to x. Using *p gets the value of x.
Go
x := 10
p := &x
fmt.Println(*p) // prints 10
The function changes the original x by using a pointer.
Go
func changeValue(val *int) {
    *val = 20
}
x := 10
changeValue(&x)
fmt.Println(x) // prints 20
Sample Program

This program shows how a pointer lets the function changeValue modify the original variable x.

Go
package main

import "fmt"

func main() {
    x := 5
    fmt.Println("Before change:", x)

    changeValue(&x)

    fmt.Println("After change:", x)
}

func changeValue(val *int) {
    *val = 10
}
OutputSuccess
Important Notes

Without pointers, functions get a copy of the value and cannot change the original.

Using pointers carefully helps avoid bugs and improves performance.

Summary

Pointers let you work directly with the memory address of variables.

They allow functions to change original data, not just copies.

Pointers help save memory and improve program speed.