0
0
Goprogramming~5 mins

Passing values vs pointers in Go

Choose your learning style9 modes available
Introduction

Passing values copies the data, while passing pointers shares the original data. This helps control if changes affect the original or just a copy.

When you want to keep the original data safe from changes.
When you want a function to update the original data.
When you want to save memory by not copying large data.
When you want to share data between parts of your program.
When you want to avoid slow copying of big structures.
Syntax
Go
func functionName(valueType value) {
    // code using value
}

func functionName(pointerType *valueType) {
    // code using pointer
}

Passing by value copies the data into the function.

Passing by pointer sends the address, so the function can change the original data.

Examples
First function changes only its copy. Second function changes the original variable through the pointer.
Go
func updateValue(x int) {
    x = 10
}

func updatePointer(x *int) {
    *x = 10
}
Shows how passing value does not change original, but passing pointer does.
Go
var a int = 5
updateValue(a)
// a is still 5

updatePointer(&a)
// a is now 10
Sample Program

This program shows the difference between passing a value and passing a pointer. The first function call does not change the original variable. The second function call changes it.

Go
package main

import "fmt"

func changeValue(val int) {
    val = 100
}

func changePointer(ptr *int) {
    *ptr = 100
}

func main() {
    a := 50
    fmt.Println("Before changeValue:", a)
    changeValue(a)
    fmt.Println("After changeValue:", a)

    fmt.Println("Before changePointer:", a)
    changePointer(&a)
    fmt.Println("After changePointer:", a)
}
OutputSuccess
Important Notes

Use pointers when you want to modify the original data inside a function.

Passing large structs by pointer can improve performance by avoiding copying.

Be careful with pointers to avoid unexpected changes or nil pointer errors.

Summary

Passing by value copies data; changes inside function do not affect original.

Passing by pointer shares the original data; changes inside function affect original.

Choose based on whether you want to protect or modify the original data.