Passing Pointers to Functions
Start with Passing Pointers to Functions
A function can accept a pointer parameter when it intentionally needs to update a variable owned by its caller.
What you’ll learn
- Explain the main purpose of passing pointers to functions.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Define func increase(n *int) and call it with increase(&total). The pointer parameter is a copy of the address, but dereferencing it reaches the same integer the caller supplied.
Use a pointer when shared mutation is part of the function’s contract. For small immutable-style calculations, passing and returning ordinary values is often easier to reason about.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import "fmt"
func increase(n *int) { *n += 5 }
func main() {
total := 10
increase(&total)
fmt.Println("Total:", total)
}
Output
Total: 15Trace what the program does
The call passes the address of total. The local parameter n holds a copy of that pointer. The assignment *n += 5 changes total from 10 to 15.
Avoid common mistakes
- Calling a function with an
intwhen it requires*intis a type mismatch. - A pointer argument itself is still passed by value; what is shared is its referent.
Try it yourself
Write double(n *int) that doubles the caller’s integer and test it with 7.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Passing Pointers to Functions in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.