Go by Example: Functions

In Go, functions are declared using the `func` keyword followed by the function name, a list of parameters, and a return type. Functions can return multiple values, and can have named or anonymous parameters.

Here’s an example of a simple function that takes two integers as parameters and returns their sum:

``````package main

import "fmt"

func add(x int, y int) int {
return x + y
}

func main() {
sum := add(42, 13)
fmt.Println(sum)
}``````

Output:

``55``

Here’s an example of a function that returns multiple values:

``````package main

import "fmt"

func swap(x, y int) (int, int) {
return y, x
}

func main() {
a, b := swap(42, 13)
fmt.Println(a, b)
}``````

Output:

``13 42``

Go also supports anonymous functions, also known as closures, which can be used to create functions dynamically and pass them as arguments to other functions. Here’s an example:

``````package main

import "fmt"

func main() {
add := func(x, y int) int {
return x + y
}
sum := add(42, 13)
fmt.Println(sum)
}``````

Output:

``55``

Functions are a fundamental building block in Go, and are used to encapsulate logic and promote code reuse. They can also be used to create higher-order functions, which are functions that take other functions as arguments or return functions as results.

In Go, functions can also have variadic parameters, which allow them to accept a variable number of arguments. Variadic parameters are indicated by the `...` syntax in the parameter list.

Here’s an example of a function that calculates the sum of a variable number of integers:

``````package main

import "fmt"

func sum(nums ...int) int {
total := 0
for _, num := range nums {
total += num
}
}

func main() {
result := sum(1, 2, 3, 4, 5)
fmt.Println(result)
}``````

Output:

``15``

Go also supports recursive functions, which are functions that call themselves. Here’s an example of a recursive function that calculates the factorial of a number:

``````package main

import "fmt"

func factorial(n int) int {
if n == 0 {
return 1
}
return n * factorial(n-1)
}

func main() {
result := factorial(5)
fmt.Println(result)
}``````

Output:

``120``

Functions can also be used as values, which allows for powerful functional programming techniques in Go. For example, you can pass functions as arguments to other functions, or you can create functions that return other functions as results.

In Go, functions are first-class citizens, which means that they can be treated like any other value in the language, such as integers or strings. This makes functions a flexible and powerful tool for solving complex problems in Go.