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
func add(x int, y int) int {
	return x + y
}

The returned type is written after the parentheses.

Parameters can be written in shortcut syntax:

func add(x, y int) int 

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, xand ydo not have to be declared right within the function:

func split(sum int) (x, y int) {
	x = sum * 4 / 9
	y = sum - x
	return
}

While at first glance, the returndoesn’t return anything, it returns the named values by default, if we do not specify anything else.

  • returnstatement 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.

func doubleVal(x int) int {
	return x * 2
}
 
func compute(fn func(int) int) int {
	return fn(3)
}
 
func main() {
	fmt.Println(compute(doubleVal))

Closures

A closure is a function that references variables from outside its body:

var x = 42 
 
func addToX(y int) int {
	return x + y 
}

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:

func() { fmt.Println("Self-invoking function") }()

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:

var add = func(a int, b int) int {
	return a + b
}

This function can then be called as usual: add(2, 1).

Next Chapter: If, else and switch