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
- The names document what comes back.
- A bare
returnsends the current values. - Use them for the defer trick, not to save typing.
Keywords and builtins used here
defererrorfuncifreturn
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.
Step 4 of 4 in defer, panic & recover, step 13 of 15 in Errors.