Introduction

Functions are fundamental building blocks in Go, allowing you to organize and reuse code. In this guide, we'll explore how to define and call functions in Go, providing sample code and detailed explanations.


Defining Functions

In Go, you define a function using the func keyword followed by the function name, parameters, return type, and the function body. Here's a simple function that adds two numbers and returns the result:

                            package main
import "fmt"
// Define a function named "add" that takes two integers as parameters and returns an integer.
func add(a, b int) int {
return a + b
}
func main() {
result := add(5, 3)
fmt.Println("5 + 3 =", result)
}

In this code, we define the add function that takes two integer parameters (a and b) and returns their sum. The main function calls the add function and prints the result.


Returning Values

Functions can return one or more values in Go. You specify the return type(s) in the function signature. Here's an example of a function that returns both the sum and product of two numbers:

                            package main
import "fmt"
// Define a function named "sumAndProduct" that takes two integers as parameters and returns two integers.
func sumAndProduct(a, b int) (int, int) {
sum := a + b
product := a * b
return sum, product
}
func main() {
s, p := sumAndProduct(5, 3)
fmt.Println("Sum:", s)
fmt.Println("Product:", p)
}

The sumAndProduct function returns both the sum and product of the input numbers. In the main function, we receive and print the results.


Variadic Functions

Go supports variadic functions, which can accept a variable number of arguments. The arguments are treated as a slice inside the function. Here's an example of a variadic function that calculates the sum of multiple numbers:

                            package main
import "fmt"
// Define a variadic function named "sum" that takes any number of integers and returns their sum.
func sum(numbers ...int) int {
total := 0
for _, num := range numbers {
total += num
}
return total
}
func main() {
s := sum(5, 3, 10, 7)
fmt.Println("Sum:", s)
}

The sum function can accept any number of integer arguments and returns their sum.


Anonymous Functions (Closures)

Go allows you to define anonymous functions, also known as closures. These functions can be assigned to variables and used as arguments to other functions. Here's an example of an anonymous function:

                            package main
import "fmt"
func main() {
// Define and call an anonymous function.
result := func(a, b int) int {
return a * b
}(5, 3)
fmt.Println("Result:", result)
}

In this code, we define an anonymous function that multiplies two numbers and immediately call it with the values 5 and 3. The result is printed to the console.


Further Resources

To further explore Go functions, consider these resources: