All lessons

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.

Go · Power Tools: Multiple Returns, Closures & Slices0/5 cleared

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.

You
Binary Treant

Loading editor...

Ln 1, Col 1Spaces: 4
Sign up to fightTarget output: 3 2