Search⌘ K

Learning About Functions

Explore how to declare and use functions in Go, including multiple return values, named returns, variadic arguments, and anonymous functions. This lesson provides essential knowledge for managing function behavior and prepares you for handling errors and concurrency in future topics.

Functions in Go are what we’d expect from a modern programming language. There are only a few things that make Go functions different:

  • Multiple return values are supported

  • Variadic arguments

  • Named return values

The basic function signature is as follows:

Go (1.18.2)
func functionName([varName] [varType], ...) ([return value],[return value], ...) {
}

Let's make a basic function that adds two numbers together and returns the result:

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

As we can see, this takes in two integers, x and y, adds them together, and returns the result (which is an integer). Let's show how we can call this function and print its output:

Go (1.18.2)
package main
import "fmt"
func add(x int, y int) int {
return x + y
}
func main() {
result := add(2, 2)
fmt.Println(result)
}

We can simplify this function signature by declaring both x and y types with a single int keyword:

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

This is equivalent to the previous one.

Returning multiple values and named results

In ...