typestar

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

  1. Returning (T, error) is the standard shape.
  2. Variadic nums ...int accepts any count.
  3. A named result lets return stand alone.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 6 in Functions, step 10 of 30 in Language basics.

← Previous Next →