typestar

defer and cleanup in Go

Guaranteed cleanup, and returning a deferred error.

func copyFile(src, dst string) (err error) {
    in, err := os.Open(src)
    if err != nil {
        return fmt.Errorf("open %s: %w", src, err)
    }
    defer in.Close()

    out, err := os.Create(dst)
    if err != nil {
        return err
    }
    defer func() {
        if cerr := out.Close(); err == nil {
            err = cerr
        }
    }()
    _, err = out.ReadFrom(in)
    return err
}

How it works

  1. defer runs when the function returns, in LIFO order.
  2. A named result lets a deferred closure set the error.
  3. %w wraps the failure with context.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
311
Tokens
102
Three-star pace
105 tpm

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

Type this snippet

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

← Previous Next →