Functions and multiple returns in Go
Go's signature style: values plus an error.
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("divide by zero")
}
return a / b, nil
}
func sum(nums ...int) (total int) {
for _, n := range nums {
total += n
}
return
}
How it works
- Returning
(T, error)is the standard shape. - Variadic
nums ...intaccepts any count. - A named result lets
returnstand alone.
Keywords and builtins used here
errorfloat64forfuncifintrangereturn
The run, in numbers
- Lines
- 13
- Characters to type
- 201
- Tokens
- 62
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 41 seconds.
Step 1 of 6 in Functions, step 10 of 30 in Language basics.