Functions
Functions
Define functions with func
.
Return types
Return multiple values
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.
Closures can lead to unexpected behavior in Concurrency.
In the example bellow, count
is remembered through increment
executions, because counter
ends up allocated in the heap since the anonymous function references it.
Referencing a outer scope variable is always by reference, that is how the value is changed.
And because of the allocation in the Heap, it will not be Garbage Collected until the reference is lost.
The main()
function
main()
functionThere is also the need for a main()
function to be defined. Which will be the entrypoint function by default to be executed.
There can only be ONE main()
function in your package main
.
If making a utility package there is no need for a main()
function. Because it is not intended to be executed as a program, but to be imported by other packages.
Last updated