package main import "fmt" func changeValue(x int) { x = 10 } func main() { a := 5 changeValue(a) fmt.Println(a) }
The function changeValue receives a copy of a. Changing x inside the function does not affect a in main. So, the output is 5.
package main import "fmt" func changeValue(x *int) { *x = 10 } func main() { a := 5 changeValue(&a) fmt.Println(a) }
The function changeValue receives a pointer to a. It changes the value at that memory address to 10. So, a is updated and the output is 10.
Pointers let functions access and change the original variable by using its memory address. This is important because Go passes arguments by value by default, so without pointers, functions cannot modify the caller's variables.
package main func main() { var a int = 5 var p *int = &a p = p + 1 }
Go does not support pointer arithmetic. Trying to add 1 to a pointer causes a compilation error because the types do not match.
Go uses pointers to make memory management explicit. This helps programmers understand when data is shared or changed, avoiding hidden behaviors that references might cause.