Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

It's purely a question of scopes, as indicated by the equivalent code in the article:

    for _, elem := range elems {
      elem := elem
      ... &elem ...
    }
Nothing beyond regular lexical scoping and Go's ordinary assignment semantics are necessary to see how this works. The second 'elem' has a narrower scope than the first (it is limited to the loop body). Abusing Go syntax, you can think of the current semantics as follows:

    {
      var elem Elem
      for _, elem = range elems {
        ... &elem ...
      }
    }
Here 'elem' scopes outside the loop body, and so is reassigned on every iteration of the loop (and &elem evaluates to the same address on every iteration).

>the thought experiment about non-lexical scopes

It's not just a thought experiment. There are languages with dynamically scoped variables (e.g. global vars in Common Lisp).



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

Search: