News for hackers. Stuff that matters.
Re:Griping about Go by nvarsj on Friday February 08, 2019 @06:05AM (#19113132)
Defer also encourages the unsafe behavior of not checking error results. You can't propagate errors from it. About the best you can do is wrap whatever function you were deferring in another function, and then panic if there is an error.
Re:Griping about Go by shabbyrobe on Friday February 08, 2019 @06:25AM (#19113235)
You can actually propagate errors from it. It's not pretty but it works:

    func Pants() (rerr error) {
        defer func() {
            if err := doStuff(); err != nil && rerr == nil {
                rerr = err
            }
        }()
        // ...
        return nil
    }
I use this function all the time with `io.Closer` implementations:

    func DeferClose(err *error, closer io.Closer) {
        cerr := closer.Close()
        if *err == nil && cerr != nil {
            *err = cerr
        }
    }

    func Pants() (rerr error) {
        f, _ := os.Open(...)
        defer errtools.DeferClose(&rerr, f)
        // ...
        return nil
    }