Power Tools: Multiple Returns, Closures & Slices
10 min · Go
Return more than one value, write inline function literals, and build your own map/filter over a slice.
Enemy 1 of 5
Multiple return values
One of Go's more distinctive features: a function can return more than one value at once. You list the return types in parentheses, separated by commas — func divmod(a, b int) (int, int) returns two ints — and the return statement itself just lists both values, also comma-separated: return a / b, a % b.
On the calling side, := can unpack both returned values into two new variables in a single line: q, r := divmod(17, 5). This is commonly used in idiomatic Go for pairing a result with an error (value, err := someOperation()), even though this lesson's example uses it for a quotient and remainder instead.
Loading editor...