V Forum

[ log in ]

How should I understand arrays in memory?

SleepyRoy 2019-06-13 00:47
Here's a short program and its results on playground.
fn main() {
mut a := [1, 2, 3]
mut b := a
loc1 := &a
loc2 := &b
println(loc1 == loc2) // => false
b[0] = 0
println(a) // => [0, 2, 3]
println(b) // => [0, 2, 3]
}
The first result ("false") indicates a and b are stored at different locations in memory. However, changing b[0] affects both a and b. I'm somewhat confused about this ...
dcurrie 2019-06-13 01:49
I suspect the first result ("false") indicates a and b are at different locations in memory, but they happen to point to the same array. This is just like arrays in C.
medvednikov 2019-06-13 11:36
Yes, the same in Go.

There's an `array.clone()` method if you want a real copy. I'm not sure it's public yet, I'll make it public in V 0.0.11.

The convention is not to use operators for expensive operations (O(n) in this case).



Powered by Vorum, open-source blogging/forum software written in V