Explain value passing
Explain value passing
Go passes arguments by value: a parameter receives a copy of the argument value. Reassigning an ordinary integer parameter does not change the caller’s integer variable. Returning a new value and assigning it in the caller is a simple way to update state.
package main
import "fmt"
func change(n int) { n = 99; fmt.Println(n) }func main() { x := 7 change(x) fmt.Println(x)}The function prints its local n, while x remains 7. A parameter name does not make it an alias for the original variable.
Return the updated value
package main
import "fmt"
func increase(n int) int { return n + 1 }func main() { x := 7 x = increase(x) fmt.Println(x)}The caller explicitly assigns the result. Pass-by-value does not imply deep copying: a slice value can refer to shared backing storage, and a copied pointer can still refer to the same variable. These cases are explored in later chapters.
Try it locally
Write discount(price int) int returning price minus 5. Start with price 20, print the result without assignment, then print the original price, then assign and print the updated price.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Functions 06: Explain value passing
Check the lesson objective before moving on.
What happens to the caller’s int after a parameter is reassigned?
Does passing by value imply deep copying all reachable data?