Passing values copies the data, while passing pointers shares the original data. This helps control if changes affect the original or just a copy.
Passing values vs pointers in 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.
func updateValue(x int) { x = 10 } func updatePointer(x *int) { *x = 10 }
var a int = 5 updateValue(a) // a is still 5 updatePointer(&a) // a is now 10
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.
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) }
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.
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.