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

Share this video with your friends

Send Tweet

README for this exercise.

hipertracker
hipertracker
~ 4 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 Biscardi(instructor)
~ 4 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.