user419050
user419050

Reputation: 151

Acessing values in nested array

I'm learning Rust and I wanted to write program that would take a (randomly generated) bowling sheet and generate the score. I now know that I will have to use Rusts Vecs instead of arrays but I got stuck at accessing the value from the nested arrays so I would like to find the solution before I re-write it.

What I wanted to do is access the individual values and run some logic on them, but I got stuck at the "accessing values" part, this is what I came up with (but it doesn't work):

let sheet: [[u32; 2]; 10] = [[1, 3], [0, 6], [9, 0], [0, 5], [5, 3], [4, 2], [1, 4], [2, 3], [3, 0], [4, 4]];

for frame in 0..sheet.len() {
    for score in 0..sheet[frame].len() {
        println!("{}", sheet[frame[score]]);
    }
}

Upvotes: 2

Views: 361

Answers (1)

HJVT
HJVT

Reputation: 2192

You should clarify what exactly do you mean by 'accessing individual values', but from your code i'd assume that you just want to iterate over every score. Here's how you do it with for loops:

let sheet = [[1, 3], [0, 6], [9, 0], [0, 5], [5, 3], [4, 2], [1, 4], [2, 3], [3, 0], [4, 4]];

for frame in sheet {
    // On the first iteration frame will be == [1, 3], then [0, 6], etc
    for score in frame {
        // on first iteration score will be == 1, then 3, then 0, etc
        println!("{}", score);
    }
}

Upvotes: 2

Related Questions