README for this exercise.
A Community Resource means that it’s free to access for all. The instructor of this lesson requested it to be open to the public.
Chris Biscardi: Move_semantics2 has the same structure as move_semantics1 where we have a vec0 which is the new vec and a mutable vec1 that we fill with a number of values. We then print out some information using the println! Macro, push(88) in, and print again.
Note that this time, we have a borrow of move value: 'vec0'. This is because vec does not implement the copy trait, so it cannot be automatically copied, which means that we have to move the value into the fill_vec() function.
When we call vec0.length on line 13, we've already moved vec0 into the fill_vec() function, so we no longer have access to it. When we try to borrow it to get the length, we can't. We can fix this in a number of ways.
For example, if we clone vec0 as the argument to fill_vec(), then we're not moving vec0, and such can access it later. Instead of cloning, we could also make this a reference which means that the value that we passed into fill_vec() would also need to be a reference.
Adding a reference is not enough. The returned vec raise an error
20 | fn fill_vec(vec: &Vec<i32>) -> Vec<i32> {
| -------- expected Vec<i32>
because of return type
...
27 | vec
| ^^^
| |
| expected struct Vec
, found &Vec<i32>
| help: try using a conversion method: vec.to_vec()
|
= note: expected struct Vec<i32>
found reference &Vec<i32>
right, you'd have to also move the .clone()
into fill_vec
, thereby making a copy of the data in vec0
.
fn fill_vec(vec: &Vec<i32>) -> Vec<i32> {
let mut vec = vec.clone();
vec.push(22);
vec.push(44);
vec.push(66);
vec
}
A third option would also be to make vec0 mutable as shown in this playground link and pass an exclusive reference (maybe better known as a mutable reference) to fill_vec
. Note that in this case because the reference is mutable, we get rid of the return type as well.