Functions

Functions

Define functions with func.

// If both are same type
func name(param1, param2 string) {}

// If different types
func name(param1 int, param2 string) {}

Return types

func name(param1, param2 string) string {
    return param1
}

Return multiple values

func name(param1 int, param2 string) (int, string) {
    return param1, param2
}

var a, b string = name("A", "B")

Auto declare & return variables

Specify names of returned variables, and Go will auto declare AND return them, when return is called.

Functions as parameters

Functions as values

Anonymous functions

Variadic functions

Functions that work with any amount of parameters.

Add other parameters, but only BEFORE the numbers parameter.

Closures

A closure is a function that captures variables from an outer scope.

In the example bellow, count is remembered through increment executions, because counter ends up allocated in the heap since the anonymous function references it.

The main() function

There is also the need for a main() function to be defined. Which will be the entrypoint function by default to be executed.

Last updated