Hacker News new | past | comments | ask | show | jobs | submit login

Wouldn't this work by reference? The referenced value would be the same in both contexts.

Honestly, am I missing something?




The syntax of defer is a function call, but it isn't called like a normal function: the arguments are evaluated at the time the defer is encountered, and then the function is called later. That's one reason why defer is very often called with an anonymous function, so that variables can be captured.

So, the version that prints 1 is

    func a() {
        i := 0
        defer func(){
          fmt.Println(i)
        }()
        i++
        return
    }





Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: