0
0
Goprogramming~5 mins

Pointer behavior in functions in Go

Choose your learning style9 modes available
Introduction

Pointers let you share and change data directly inside functions without copying it. This helps save memory and lets functions update values outside their own space.

When you want a function to change a variable from outside its own code.
When you want to avoid copying large data to keep your program fast.
When you need to share the same data between different parts of your program.
When you want to return multiple values by changing variables passed to a function.
Syntax
Go
func functionName(param *Type) {
    // use *param to access or change the value
}

The * before a type means the parameter is a pointer to that type.

Use *param inside the function to get or set the actual value.

Examples
This function takes a pointer to an int and sets the value it points to 10.
Go
func updateValue(x *int) {
    *x = 10
}
This function prints the value pointed to by the pointer.
Go
func printValue(x *int) {
    fmt.Println(*x)
}
Sample Program

This program shows how a function can change a variable's value using a pointer. We pass the address of number to changeNumber. Inside the function, the value at that address is changed to 42. The change is visible outside the function.

Go
package main

import "fmt"

func changeNumber(num *int) {
    *num = 42
}

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

Passing a pointer means the function can change the original variable.

Use & to get the address of a variable when calling the function.

Use * inside the function to access or modify the value the pointer points to.

Summary

Pointers let functions change variables outside their own scope.

Use & to send a variable's address, and * to access or change the value inside the function.

This helps save memory and allows direct updates to data.