Passing Values to Functions with Parameters
- A function can receive data through parameters, which behave like local variables inside the function body.
- Declare parameters immediately after the function name, inside parentheses. For each one, write the parameter’s name followed by its type. If the function needs several parameters, list them in sequence and separate them with commas.
Syntax:
func FunctionName(param1 type, param2 type, param3 type) {
// code to execute
}
Passing a Parameter to a Function
- In this example, the function receives a single string argument, fname.
- Every time we call the function with a different first‑name value, it prints a greeting that combines that name with the shared last name “Refsnes”.
Example:
package main
import "fmt"
// greetFamily prints a greeting with a common last name.
func greetFamily(fname string) {
fmt.Printf("Hello %s Refsnes\n", fname)
}
func main() {
greetFamily("Liam")
greetFamily("Jenny")
greetFamily("Anja")
}
Output
Hello Liam Refsnes
Hello Jenny Refsnes
Hello Anja Refsnes
Note:
- Keep in mind that a parameter becomes an argument the moment you pass a value to it. In the earlier example, fname is the parameter, and the specific values Liam, Jenny, and Anja are the arguments supplied to that parameter.
Working with Multiple Parameters in Go
A single function can take any number of parameters—just separate them with commas inside the parentheses.
Example:
package main
import "fmt"
// familyName accepts a first name (string) and an age (int).
func familyName(fname string, age int) {
fmt.Printf("Hello %d‑year‑old %s Refsnes\n", age, fname)
}
func main() {
familyName("Liam", 3)
familyName("Jenny", 14)
familyName("Anja", 30)
}
Output
Hello 3‑year‑old Liam Refsnes
Hello 14‑year‑old Jenny Refsnes
Hello 30‑year‑old Anja Refsnes
Note:
- Remember: if a function defines several parameters, your call to that function must supply the same number of arguments, and they must appear in the exact order the parameters were declared.