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 4 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.