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.
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:
Let's make a basic function that adds two numbers together and returns the result:
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:
We can simplify this function signature by declaring both x and y types with a single int keyword:
This is equivalent to the previous one.
Returning multiple values and named results
In ...