Introduction
In Go, functions can accept parameters, which act as variables inside the function. These parameters allow functions to receive input data and perform operations on it. Let's explore how to define functions with parameters and how to pass arguments to them.
Parameters and Arguments
Parameters are variables declared in the function definition, and arguments are the values passed to the function when it is called.
Function with Parameter Example
Consider a function greetUser
that takes a single parameter userName
of type string. This function greets the user by appending a common salutation "Hello" to the provided user name.
package main
import "fmt"
func greetUser(userName string) {
fmt.Println("Hello", userName)
}
func main() {
greetUser("Alice")
greetUser("Bob")
greetUser("Charlie")
}
Output
Hello Alice
Hello Bob
Hello Charlie
In this example, "Alice"
, "Bob"
, and "Charlie"
are the arguments passed to the greetUser
function. Inside the function, userName
acts as a parameter that receives these values.
Multiple Parameters
Functions in Go can have multiple parameters. Each parameter must specify its type.
package main
import "fmt"
func greetUserWithAge(userName string, age int) {
fmt.Printf("Hello, %s! You are %d years old.\n", userName, age)
}
func main() {
greetUserWithAge("Alice", 25)
greetUserWithAge("Bob", 30)
}
Output
Hello, Alice! You are 25 years old.
Hello, Bob! You are 30 years old.
In this example, the greetUserWithAge
function takes two parameters: userName
of type string and age
of type int. The function is called twice with different arguments, providing both a user name and an age.
Conclusion
Understanding how to define functions with parameters and pass arguments to them is essential for building flexible and reusable code in Go. By leveraging parameters and arguments effectively, developers can create functions that handle various inputs and perform diverse operations. Experiment with different parameter types and function signatures to fully utilize the power of functions in Go.