Parameters, multiple returns, variadic, closures, and defer.
Function Basics
Functions are declared with func, then the name, parameters, and return type.
func add(a int, b int) int {
return a + b
}
If consecutive parameters share a type, you can write the type once:
func add(a, b int) int { return a + b }
Calling functions
go playground
Loading...
Functions are values
In Go, functions are first-class values — you can pass them around like any other data.
go playground
Loading...
Here double is an anonymous function assigned to a variable.
func(int) int is the type of "a function that takes one int and returns one int".
No optional/default arguments
Go doesn't have default values for parameters or named arguments. The Go way is to provide additional functions or pass a struct:
// Awkward in some languages, normal in Go:
type ListOptions struct {
Limit int
Cursor string
}
func List(opts ListOptions) ([]Item, error) { ... }
No overloading either
Two functions can't share a name with different signatures. The Go way is just to pick different names:
func PrintInt(x int) { ... }
func PrintFloat(x float64) { ... }
// — or use generics (Chapter 13).
What's the type of an anonymous function `func(s string) int { return len(s) }`?