Functions can accept more than one parameter, allowing you to pass multiple pieces of data into a function at once. This makes functions even more flexible and powerful.
To define multiple parameters, separate them with commas in the parameter list:
func introduce(name string, age int) {
fmt.Println(name, "is", age, "years old")
}
func main() {
introduce("Goku", 30)
introduce("Vegeta", 35)
}
// Output:
// Goku is 30 years old
// Vegeta is 35 years old
Each parameter must have its type specified, and when calling the function, you must pass arguments in the same order as the parameters are defined.
Let's improve our power level checker to also display the character's name:
func checkPowerLevel(name string, powerLevel int) {
fmt.Println("Checking", name)
if powerLevel > 9000 {
fmt.Println("It's over 9000!")
} else {
fmt.Println("Nothing to worry about")
}
}
func main() {
checkPowerLevel("Goku", 9001)
checkPowerLevel("Piccolo", 8000)
}
// Output:
// Checking Goku
// It's over 9000!
// Checking Piccolo
// Nothing to worry about
When calling a function with multiple parameters, the order is crucial:
func displayStats(name string, health int, power int) {
fmt.Println(name, "- Health:", health, "Power:", power)
}
// Correct order
displayStats("Goku", 100, 9000)
// Wrong order - will compile but give wrong results
displayStats("Vegeta", 8500, 90) // Swapped health and power!
When you have many related values, passing individual parameters can become error-prone. Instead, you can group related data into a struct and pass the entire struct:
type Fighter struct {
Name string
PowerLevel int
Health int
}
func checkPowerLevel(fighter Fighter) {
fmt.Println("Checking", fighter.Name)
if fighter.PowerLevel > 9000 {
fmt.Println("It's over 9000!")
} else {
fmt.Println("Nothing to worry about")
}
}
func main() {
goku := Fighter{
Name: "Goku",
PowerLevel
This approach has several advantages:
// Multiple individual parameters - prone to errors
func checkStats(name string, power int, health int, speed int) {
// ...
}
checkStats("Goku", 9000, 100, 85)
checkStats("Vegeta", 90, 8500, 80) // Oops! Mixed up power and health
// Using a struct - safer and clearer
type Fighter struct {
Name string
Power int
Health int
Speed int
}
func checkStats(fighter Fighter) {
// ...
For this challenge, create a function called performAttack that accepts three parameters
The function should:
"Performing [name]""Damage: [damage]""High energy attack!""Standard attack"In your main function, call performAttack with the following parameters:
Expected output:
Performing Kamehameha
Damage: 150
High energy attack!
Performing Punch
Damage: 20
Standard attack