Chooce video playback speed
speed:1
  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

InstructorChris Biscardi

Share this video with your friends

Send Tweet

README for this exercise.

This lesson is a Community Resource

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.