func swap(a, b int) (int, int) { return b, a}x, y := 1, 2x, y = swap(x, y) // x = 2, y = 1
Ignoring return values:
x, _ = getCoords()
Named return values:
With named return values, you can use return without specifying values. The function automatically returns the named variables.
func calculate(x int) (result int) { result = x * x return}
Variadic functions:
Variadic functions accept zero or more arguments of the same type, which are treated as a slice inside the function.
func sum(numbers ...int) int { total := 0 for _, number := range numbers { total += number } return total}sum(2, 5, 7, 10) // 24
First-class functions:
First-class functions are functions that can be assigned to variables, passed as arguments to other functions, and returned as values from other functions.
In Go, all function arguments are passed by value. When a value is passed to a function, Go creates a copy of that value and the function operates on the copy. Changes made to the parameter inside the function do not affect the original variable.
However, some types contain internal references to underlying data. When such a value is copied, the underlying data itself is not duplicated, only the internal reference is copied, allowing the function to modify the shared underlying data.
Even when a value allows modification of shared underlying data, the variable itself is still passed by value. Reassigning the parameter inside a function only changes the local copy and does not affect the original variable in the caller.
The defer keyword allows us to execute a function or line of code at the end of the current function's execution. This is useful for cleaning up resources, such as closing files or connections.