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.
// No auto declaring & return
func name(param1 int, param2 string) (int, string) {
var ra = param1
var rb = param2
return ra, rb
}
// Auto declare & return
func name(param1 int, param2 string) (ra int, rb string) {
ra = param1
rb = param2
return
// Or you can explicitly return them though
return ra, rb
}
Functions as parameters
func upper(text string) string {}
func name(param1 string, transform func(string) string) {
return transform(param2)
}
a := name("a", upper)
Functions as values
func upper(text string) string {}
func lower(text string) string {}
func decide(whichOne string) func(string) string {
if ... {
return upper
}
return lower
}
f := decide("upper") // f will have the upper function
f("a") // A
Anonymous functions
func name(param1 string, transform func(string) string) {
return transform(param2)
}
a := name("a", func (text string) string {
...
})
Variadic functions
Functions that work with any amount of parameters.
func name(numbers ...int) int[] {
return numbers
}
Add other parameters, but only BEFORE the numbers
parameter.
func name(name string, numbers ...int) int[] {
return numbers
}
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.
func counter() func() int {
counter := 0
return func () int {
count++
return count
}
}
increment := counter()
increment() // 1
increment() // 2
increment() // 3
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