Function Parameters
Start with Function Parameters
Parameters let the same function work with different values. They are local names that receive arguments supplied by the caller.
What you’ll learn
- Explain the main purpose of function parameters.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
A parameter declaration pairs a name and type: func greet(name string). The caller passes an argument such as greet("Maya"). Inside the function, name is a local variable initialized from that argument.
Adjacent parameters of the same type can share one type declaration, for example func add(a, b int). Go passes argument values into parameter variables. Changing a parameter such as an int does not update the original caller variable.
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 add(a, b int) {
fmt.Println("Sum:", a+b)
}
func main() {
x := 7
y := 5
add(x, y)
fmt.Println("Original x:", x)
}
Output
Sum: 12
Original x: 7Trace what the program does
The call add(x, y) initializes parameter a to 7 and b to 5. The function prints 12, then returns to main. The original variable x remains 7.
Avoid common mistakes
- Arguments must match parameter types; Go does not automatically convert arbitrary numeric variables.
- Parameter names are local to the function, not global variables shared with the caller.
Try it yourself
Change the function to print the product of two numbers. Call it twice with different arguments.
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 Function Parameters 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.