sergej.p
sergej.p

Reputation: 115

How to change vec value of elements by index?

let mut vec1 = vec![0,0,0,0];
let vec2 = vec![1,3,2,0];

for v in vec2.iter(){
   vec1[v] += 1;
}

My example does not work. How do I change values correctly?

Upvotes: 6

Views: 5513

Answers (2)

akuiper
akuiper

Reputation: 215117

Your index is behind a reference and it needs to be of type usize, so make sure you destructure it:

for &v in vec2.iter(){
   vec1[v] += 1;
}

And also to be safe, explicitly cast v as usize:

for &v in vec2.iter(){
   vec1[v as usize] += 1;
}

Playground.

Upvotes: 6

richerarc
richerarc

Reputation: 250

This will run and print [1,1,1,1]:

fn main() {
    let mut vec1 = vec![0,0,0,0];
    let vec2 = vec![1,3,2,0];

    for v in vec2.iter(){
        vec1[*v] += 1;
    }
    
    dbg!(vec1);
}

Playground

Upvotes: 3

Related Questions