On Fri, Sep 1, 2017 at 7:32 AM,  <mspre...@us.ibm.com> wrote:
>
> This just bit me.  I wonder if the discussion above missed the critical
> point.  Looking at https://golang.org/ref/spec#Address_operators, I see that
> a variable is considered _addressable_ and that's all there is to it.  Now,
> in C and other such languages, there is a critical distinction about
> addresses that is relevant: is the address on the stack or on the heap?
> Since the Go doc does not mention this distinction, I wonder if all
> variables are on the heap.  That would explain why all variables are
> addressable.  In the example that started this thread, there is only one
> loop iteration variable; supposing it is on the heap, `&` extracts a pointer
> to it, and the loop leaves the last value in that variable.
>
> The mental model I had when I wrote my code was something like the
> following.  I supposed that Go keeps local (to a block in a function)
> variables on the stack, and the compiler knows this.  A statement like `x =
> &localVar` is equivalent to something like
> ```
> x = new(<type of localVar>)
> *x = localVar
> ```
>
> (which still seems (to me) to be the right model if we are talking about
> <constructor> instead of <localVar> --- which is what led me to think this
> way.)

When writing Go you can imagine that all variables are on the heap.

The compiler implements escape analysis optimizations that allocate
variables on the stack when it can be proven to be safe.

Ian

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