Learning About Functions
Learn about functions in Go, including variadic arguments and anonymous functions.
We'll cover the following...
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:
Press + to interact
func functionName([varName] [varType], ...) ([return value],[return value], ...) {}
Let's make a basic function that adds two numbers together and returns the result:
Press + to interact
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:
Press + to interact
package mainimport "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:
Press + to interact
func add(x, y int) int {return x + y}
This is equivalent to the previous one.