typestar

The early return in Go

Handle the error and return; the happy path stays at one indent.

func parseRun(fields []string) (string, int, error) {
    if len(fields) != 2 {
        return "", 0, fmt.Errorf("want 2 fields, got %d", len(fields))
    }

    lang := strings.TrimSpace(fields[0])
    if lang == "" {
        return "", 0, errors.New("language is empty")
    }

    tpm, err := strconv.Atoi(strings.TrimSpace(fields[1]))
    if err != nil {
        return "", 0, fmt.Errorf("parse tpm: %w", err)
    }

    return lang, tpm, nil
}

How it works

  1. Each call is followed by its check, so nothing is ignored.
  2. Wrapping at each level says where it failed.
  3. This is why Go code has so few else branches.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
388
Tokens
113
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 71 seconds.

Type this snippet

Step 3 of 3 in The error value, step 3 of 15 in Errors.

← Previous Next →