Functions, several return values and closures
A function declares its parameters and its results, and Go allows more than one of each. A function is a value: it can be stored in a variable, passed to another function and returned from one, which is what makes closures and handlers possible without a special type.
Several results
A function that can fail returns its value and an error as the last result, and the caller checks the error first. Named results, as in split, are declared in the signature and can be returned by a bare return; they are useful for a documentation comment, and dangerous in a long function because the names can be shadowed.
package main
import (
"errors"
"fmt"
)
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
func split(total int) (x, y int) {
x = total * 4 / 9
y = total - x
return
}
func main() {
q, err := divide(10, 4)
fmt.Println(q, err)
_, err = divide(1, 0)
fmt.Println("error:", err)
x, y := split(90)
fmt.Println("split:", x, y)
}
go run multi.go
2.5 <nil>
error: division by zero
split: 40 50
The error is nil when nothing went wrong, and a program tests it against nil rather than against a string. The next lesson is about that value.
Variadic parameters
A last parameter of the form ...T accepts zero or more arguments of type T, and inside the function it is a slice. A slice at the call site is spread with nums..., which passes its elements rather than the slice as one argument.
package main
import (
"fmt"
"strings"
)
func join(sep string, parts ...string) string {
return strings.Join(parts, sep)
}
func sum(nums ...int) (total int) {
for _, n := range nums {
total += n
}
return total
}
func main() {
fmt.Println(join("-", "go", "is", "fun"))
fmt.Println(join("-"))
fmt.Println(sum(1, 2, 3))
nums := []int{4, 5, 6}
fmt.Println(sum(nums...))
}
go run variadic.go
go-is-fun
6
15
The function cannot tell whether it was called with no arguments or with an empty slice, which is why a variadic function that requires at least one value checks the length. fmt.Println is variadic for the same reason.
Functions as values and closures
A function literal is an anonymous function with its own environment. The returned closure keeps the variable it captured alive, so counter hands out a function with private state that no other code can reach.
package main
import "fmt"
func counter() func() int {
n := 0
return func() int {
n++
return n
}
}
func apply(f func(int) int, values []int) []int {
out := make([]int, len(values))
for i, v := range values {
out[i] = f(v)
}
return out
}
func main() {
next := counter()
fmt.Println(next(), next(), next())
other := counter()
fmt.Println("a second counter:", other())
double := func(n int) int { return n * 2 }
fmt.Println(apply(double, []int{1, 2, 3}))
}
go run closure.go
1 2 3
a second counter: 1
[2 4 6]
Each call of counter makes a new n, which is why the second counter starts at one again. The closures lesson goes further: loop variables, capture by reference and the range-over-function iterator of Go 1.23.
No overloading
Go has no function overloading and no default arguments. A call must match the signature exactly, and the compiler counts the arguments.
package main
import "fmt"
func add(a, b int) int {
return a + b
}
func main() {
fmt.Println(add(1, 2, 3))
}
go build args.go
# command-line-arguments
./args.go:10:24: too many arguments in call to add
have (number, number, number)
want (int, int)
Exercises
- Write a function that returns the smallest and the largest value of a slice and an error for an empty one. Which result comes last?
- Turn the counter into a function that returns two closures: one increments, one reads. What happens to the state when both are discarded?
- Write apply without allocating a new slice, by passing an existing one as the destination. Which is the better signature for a library?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which result does a function that can fail return last?
Answer
error
By convention the error is the last result, and the caller tests it against nil.
-
What is a named result?
Answer
A result declared in the signature and returned by a bare return
Named results are variables of the function scope, initialised to their zero value.
-
What is a variadic parameter of type ...int inside the function?
Answer
A slice of int
The parameter is a slice, and the caller may pass zero arguments.
-
What does
f(nums...)do?Answer
It spreads a slice into the variadic parameter
The three dots pass the elements of the slice as separate arguments.
-
What does this program print?
package main import "fmt" func f(a, b int) int { return a * b } func main() { x, y := f(3, 4), f(2, 5) fmt.Println(x + y) }Answer
22
The two calls return 12 and 10, and their sum is 22.
-
What does this program print?
package main import "fmt" func split(n int) (int, int) { return n / 2, n - n/2 } func main() { a, b := split(7) fmt.Println(a, b) }Answer
3 4
Integer division gives 3, and the second result is 7-3=4.
-
What does this program print?
package main import "fmt" func makeAdder(n int) func(int) int { return func(x int) int { return x + n } } func main() { add2 := makeAdder(2) add5 := makeAdder(5) fmt.Println(add2(1), add5(1)) }Answer
3 6
Each closure captures its own n, so the adders add different numbers.
-
What does the compiler say about calling a two-parameter function with three arguments?
Answer
too many arguments in call to add
Go has no overloading or optional parameters, so the arity must match.
-
What is the zero value of an error returned by a successful call?
Answer
nil
A nil error means success, and calling a method on it panics.
-
Can a function return another function?
Answer
Yes, functions are values
A function type is an ordinary type, so a function can be a parameter and a result.
The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev