Parameters and Arguments
To hand information to a function, you give it parameters. Inside the function, each parameter behaves like a variable.
You list them in the parentheses after the function name, each with its type. You can have as many as you need; commas separate them.
Parameter Syntax
func FunctionName(param1 type, param2 type, param3 type) {
// code to be executed
}
Function With Parameter Example
In this example, familyName() takes one parameter, fname, of type string. Each call passes in a different first name, which the function uses in its message. So the first name changes from line to line while the last name stays the same.
Note: The value you pass in a call has its own name: an argument. In this example, fname is the parameter, and Liam, Jenny and Anja are the arguments.
Example
Output: Go program and captured output
package main
import ("fmt")
func familyName(fname string) {
fmt.Println("Hello", fname, "Refsnes")
}
func main() {
familyName("Liam")
familyName("Jenny")
familyName("Anja")
}
Multiple Parameters
A function is not limited to one parameter; it can take as many as you need. Here familyName() takes a name and an age.
Note: With several parameters, each call has to supply one argument per parameter, in the same order as they are declared.
Example
Output: Go program and captured output
package main
import ("fmt")
func familyName(fname string, age int) {
fmt.Println("Hello", age, "year old", fname, "Refsnes")
}
func main() {
familyName("Liam", 3)
familyName("Jenny", 14)
familyName("Anja", 30)
}