To export a function it should start with a capital letter, see Go exported name.
Each function has its signature that describes its type and consists of:
Multiple return values
Function can return multiple values, e.g.:
Named return parameters
Go’s return values may be named. These names should be used to document the meaning of the return values.
They are treated as variables defined at the top of the function.
Parentheses are required.
Named returned values are initialized with their zero values.
In case you need to name some of the returned values, use _
for the rest to remain nameless.
Naked/blank return
A return
statement without arguments returns the named return values. This is known as a “naked” return. But it’s recommended that it should be used only in short functions because they harm readability in longer functions.
Omit the type
When two or more consecutive named function parameters share a type, you can omit the type from all but the last. So x int, y int
can be shortened to x, y int
:
Variadic input parameters
The vals
will be a slice of int
values.
When calling with a slice, ...
should be specified after the variable/slice literal:
First-class citizens
Functions can be passed around as arguments or return values.
Function type declaration
Can be defined with type
keyword:
Function closures
A closure is a function value that references variables from outside its body.
For example, the adder
function returns a closure. Each closure is bound to its own sum
variable.
Methods
Nested/anonymous functions
Useful when we want to reduce the scope of the function.
To do that, function need to be assigned to a variable.
Ignore returned values
To ignore some of the returned values, use _
: