typestar

Named results in Go

Naming the results lets a deferred function edit them on the way out.

func withTiming(work func() error) (elapsed time.Duration, err error) {
    started := time.Now()
    defer func() {
        elapsed = time.Since(started)
        if err != nil {
            err = fmt.Errorf("after %s: %w", elapsed.Round(time.Millisecond),
                err)
        }
    }()

    err = work()
    return
}

How it works

  1. The names document what comes back.
  2. A bare return sends the current values.
  3. Use them for the defer trick, not to save typing.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
254
Tokens
74
Three-star pace
105 tpm

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

Type this snippet

Step 4 of 4 in defer, panic & recover, step 13 of 15 in Errors.

← Previous Next →