Functions are a way to write reusable code.
The absolute basics of functions in Go:
- Can hold 0 or more arguments
- Type is provided after the name of the parameter:
func add(x int, y int)
- A type for the return value must be provided
- If a function is not returning anything (void), leave out the return type
The returned type is written after the parentheses.
Parameters can be written in shortcut syntax:
This is the same as func add(x int, y int) int
.
Named return values
In Go, the returned values can be defined directly in the header of the function. To do so, we create parentheses instead of the return type, in which we define the named values which shall be returned. These named values exist as variables within the scope of this function.
Only in this case, x
and y
do not have to be declared right within the function:
While at first glance, the return
doesn’t return anything, it returns the named values by default, if we do not specify anything else.
return
statement without arguments returns the named return values.- This is called a naked return
- Would be the same as
return x, y
- Only works when we create named return values using parentheses
Working with function values
Functions are values in Go. They can be passed to other functions.
Closures
A closure is a function that references variables from outside its body:
Anonymous and self-invoking functions
Functions do not need to hold a name. If they are nameless, they are called anonymous. Also, functions can “execute themselves”, if you denote parentheses right after their body:
The example shows an anonymous, self-invoking function.
As we learned, functions are values. This means we can assign a function to a variable like this:
This function can then be called as usual: add(2, 1)
.
Next Chapter: If, else and switch