Go Function Parameters and Arguments: Passing Data to Functions
Understanding how to pass data to functions using parameters is fundamental to building modular and reusable Go code.
Function parameters are variables defined within the function's declaration that act as placeholders for values passed during function calls. These values, known as arguments, provide input to the function's logic. By effectively using parameters, you can create flexible and dynamic functions that can operate on different data.
Function Parameter Syntax
Go functions define parameters within parentheses following the function name. Each parameter consists of a name and its corresponding data type. Multiple parameters are separated by commas.
Syntax
func functionName(parameter1 dataType, parameter2 dataType, ...) {
// function body
}
Output
None
Example: Greeting Function with a Parameter
Let's create a simple function named greet that takes a person's name as a parameter and prints a personalized greeting:
Code Snippet
package main
import "fmt"
func greet(name string) {
fmt.Printf("Hello, %s!\n", name)
}
func main() {
greet("Alice") // Output: Hello, Alice!
greet("Bob") // Output: Hello, Bob!
}
Output
Hello, Alice!
Hello, Bob!
In this example:
greet
is the function name.name
is the parameter of typestring
.- Inside the function,
name
is used to format a greeting. - The
main
function callsgreet
twice with different arguments ("Alice" and "Bob").
Key Points About Parameters
- Pass by value: In Go, arguments are passed by value, meaning the function receives a copy of the argument's value. Changes made to the parameter within the function do not affect the original value outside the function.
- Multiple parameters: Functions can accept multiple parameters of different data types.
- Named return values: Go supports named return values, which can be used to return multiple values from a function.
- Variadic functions: Functions can accept a variable number of arguments using the
...
syntax.
Deeper Dive into Parameters
To further illustrate the concept, let's explore a function that calculates the area of a rectangle:
Code Snippet
package main
import "fmt"
func calculateArea(length float64, width float64) float64 {
area := length * width
return area
}
func main() {
result := calculateArea(5, 3)
fmt.Println("Area:", result) // Output: Area: 15
}
Output
Area: 15
This example demonstrates:
- A function with two parameters,
length
andwidth
, both of typefloat64
. - The function calculates the area and returns it as a
float64
value. - The
main
function callscalculateArea
with specific values and prints the result.
By understanding parameters and arguments, you can create well-structured and reusable functions in your Go programs.