I'm doing exercises in rustlings. In vecs2.rs, the code is:
fn vec_loop(mut v: Vec<i32>) -> Vec<i32> {
for element in v.iter_mut() {
// TODO: Fill this up so that each element in the Vec `v` is
// multiplied by 2.
element = element * 2; // error here!!!
}
// At this point, `v` should be equal to [4, 8, 12, 16, 20].
v
}
fn vec_map(v: &Vec<i32>) -> Vec<i32> {
v.iter().map(|element| {
// TODO: Do the same thing as above - but instead of mutating the
// Vec, you can just return the new number!
element * 2 // no error
}).collect()
}
but I got an error:
error[E0369]: cannot multiply `&mut i32` by `{integer}`
--> exercises/vecs/vecs2.rs:16:28
|
16 | element = element * 2; // error here!!!
| ------- ^ - {integer}
| |
| &mut i32
|
help: `*` can be used on `i32` if you dereference the left-hand side
|
16 | element = *element * 2; // error here!!!
| +
I'm confused about why we should dereference explicit in vec_loop
, but no need to dereference in vec_map
(if so, it should be *element * 2
). I'd confess that I always use reference like it is the value and never use like a pointer in other language( *some_ref
).