On Tue, Oct 11, 2016 at 12:16 PM Henry <henry.adisuma...@gmail.com> wrote:

This should work.

func Execute() (err error) {
        defer func() {
                if err == nil {
                        err = Commit()
                }
                if err != nil {
                        Rollback()
                }
        }()

        err = Process()
        return err
}

> It appears to me that defer works with the local copy of the variable,
instead of a direct reference. I think as a rule I mustn't make any
variable assignment in defer. I wonder whether this is by design.

It's WAI. *After* the `return err` statement is executed the original
version of Execute invokes the deferred func which then changed the local
`err` variable so it has no effect on the already set return value. To
change the return value in a deferred function the return variable must be
named so the deferred function can set its value.

-- 

-j

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to