Hi,

I have a doubt regarding use of enclosing function's variables inside 
functions used as "deferred".

If function literal is used as "deferred" func (say foo),  and it uses 
enclosing function's variable (say x) as one of its arguments, 
the value of x is "frozen" and func foo is called with that val.
While,  if anon function is used and value of x is changed after the defer 
statement,  new value
is reflected within deferred anon func.

In first case,  nil error is printed:  https://play.golang.org/p/GB5n3ECLY3

func log(err error) {
    println(err)
}

func foo(){
    var err error
    defer log(err)
    err = errors.New("hello")
    return
}

In second case,  non-nil error is printed: 
 https://play.golang.org/p/bm9nRn_pid

func log(err error) {
    println(err)
}

func foo(){
    var err error
    defer func() {
        log(err)
    }()
    err = errors.New("hello")
    return
}

Thanks,
Karan

-- 
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