On Wed, 23 May 2018 03:03:18 -0700 (PDT) lafolle <fghj...@gmail.com> wrote:
> Thanks Mathias for clearing this out. > > I reasoned this out by looking at the address to which `i` was > allocated to, though I wanted to _peek_ inside the slice's header to > be affirmative. But I can't clearly understand how to use unsafe > pointer. Thanks for showing how to use it. > > One thing I don't understand is that why `i` is always allocated to > same address? Is it to reduce allocations? Do other languages also > do this? Most languages do not have arrays as values and therefore this special case does not apply to them. With respect to ordinary loops, yes, that's the normal way to do it. In fact for typical loops that use integer loop variables that live only for the duration of the loop, there is no allocation. The variable is simply kept in a processor register. Even the Go compiler does that when possible. It's easier to understand when you look at a loop like this for i := 0; i < 10; i++ { ... } The "i:=0" is only executed ONCE, at the very start of the loop. So it's obvious that if an allocation is necessary, it occurs only once, as neither "i<10" nor "i++" can cause an allocation. Your loop is really just a fancy version of this same pattern. MSB -- Light travels faster than sound. This is why some people appear bright until you hear them speak. -- 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.