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.
Pointer behavior in functions in 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.
func updateValue(x *int) { *x = 10 }
func printValue(x *int) {
fmt.Println(*x)
}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.
package main import "fmt" func changeNumber(num *int) { *num = 42 } func main() { number := 5 fmt.Println("Before:", number) changeNumber(&number) fmt.Println("After:", number) }
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.
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.