This is a very basic question, but I can't figure out what is happening. I expect nested for
loops in V to work like in C and other languages. Using the following for
loops to build a 2D array A
, I get an unexpected result. What am I doing wrong?
fn main () {
mut A := [[0].repeat(3)].repeat(4)
// A = [ [0,1,2], [1,2,3], [2,3,4], [3,4,5] ]
for i := 0; i < 4; i++ {
for j := 0 ; j < 3; j++ {
A[i][j] = i + j
println( '$i, $j, ${i + j}' )
}
}
for i := 0; i < 4; i++ { println(A[i]) }
}
This is what I get:
0, 0, 0
0, 1, 1
0, 2, 2
1, 0, 1
1, 1, 2
1, 2, 3
2, 0, 2
2, 1, 3
2, 2, 4
3, 0, 3
3, 1, 4
3, 2, 5
[3, 4, 5]
[3, 4, 5]
[3, 4, 5]
[3, 4, 5]
Your array contains multiple copies of the same row object. When you modify a value, you modify it for all rows. Make a new object for each row
fn main () {
mut A := [[0].repeat(3)].repeat(4)
// A = [ [0,1,2], [1,2,3], [2,3,4], [3,4,5], [4,5,6] ]
for i := 0; i < 4; i++ {
A[i] = [0].repeat(3)
for j :=0 ; j < 3; j++ {
A[i][j] = i + j
println( '$i, $j, ${i + j}' )
}
}
for i := 0; i < 4; i++ { println(A[i]) }
}