V: no more fooling by array address, please

Created on 10 Jun 2020  路  7Comments  路  Source: vlang/v

Actually I mentioned this earlier in #4803 as a comment. But now I decide to specifically open an issue for it to prevent being omitted.

Please consider the following code that gives two methods defining and modifying [0][0] element of a 2D array.

fn main() {
        // define a 3*3 zero matrix and then modify [0][0] to 1
    mut a := [[0].repeat(3)].repeat(3)  // method 1
    println(a)
    a[0][0] = 1
    println(a)
    mut b := [][]int{len:3, init: []int{len:3, init:0}}  // method 2
    println(b)
    b[0][0] = 1
    println(b)
}

Interestingly the printed result is

[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]

This means no matter which method you use, you didn't realize your goal. Instead, all elements of first column are modified.

I call this fooling by addresses. Some languages such as Python give exactly the same behavior, which I really don't like - In above code the programmer clearly wants to modify only one element. If programmers really want to modify first column, they should write code like arr[.., 0] = 0 (BTW in order to conveniently use nD array, V should support this kind of syntax). So here I propose V resolves this issue - No more fooling by array addresses, please.

Feature Request

Most helpful comment

No, it's not intended. It'll be fixed.

All 7 comments

it's because of repeat()
if you use [][]int{len:3, init:[]int{len:3}}, it should work fine

@medvednikov I just tried both repeat and [][]int and both gave same results.

I can confirm the same behavior for both versions with V 0.1.27 a667538, on Windows 10 and Ubuntu 20. To me it also looks counter-intuitive, and if this is intended behavior it should be very clearly explained as a caveat in any docs or tutorial on using arrays in V.

No, it's not intended. It'll be fixed.

That's great! This will also solve the issues #3102 3147 and 3628.

Glad to see [][]int is fixed.
Should this issue be open until repeat is also fixed?

No, #3628 is already tracking that.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

PavelVozenilek picture PavelVozenilek  路  3Comments

choleraehyq picture choleraehyq  路  3Comments

clpo13 picture clpo13  路  3Comments

taojy123 picture taojy123  路  3Comments

markgraydev picture markgraydev  路  3Comments