I stumbled upon this problem earlier and I wonder whether this is actually 
the intended behavior of defer or a bug.

Here is the code to illustrate the problem (or you can view it in the Go 
playground at https://play.golang.org/p/s2hdAmirrl ).

package main

import (

func main() {
    err := Execute()
    //err is nil. I thought it is supposed to return the commit error?
    fmt.Printf("%v", err) 

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

    err = Process()
    return err

func Process() error {
    return nil

func Commit() error {
    return errors.New("Mocked commit error")

func Rollback() {

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.



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