1. 40
    Rustlings move_semantics2: Fixing the borrow of moved values with cloning or references
    55s

Rustlings move_semantics2: Fixing the borrow of moved values with cloning or references

Chris Biscardi
InstructorChris Biscardi
Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 3 years ago

README for this exercise.

Chris Biscardi: [0:00] 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.

[0:16] 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.

[0:28] 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.

[0:40] 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.

hipertracker
hipertracker
~ 3 years ago

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>

Chris Biscardi
Chris Biscardiinstructor
~ 3 years ago

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.

Markdown supported.
Become a member to join the discussionEnroll Today