1. 39
    Rustlings move_semantics1: Borrowing vectors as mutable
    55s

Rustlings move_semantics1: Borrowing vectors as mutable

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.

push requires a mutable references to self: the vector in question.

pub fn push(&mut self, value: T)

Chris Biscardi: [0:00] In move_semantics1, we have two vectors. We have a vec0 that is a new vector. We have vec1 which calls fill_Vec on (vector ).

[0:08] Fill_Vec takes a vector of i32s and returns a vector of i32s. Inside of fill_Vec, we create a new mut vec = vec;. Then we push three values in and return the vector.

[0:20] In our main function, we use the println! Macro to print out vec1, the length of vec1, and the content of vec1. We then push 88 into vec1, and we do the same again. The problem with this code is that we cannot borrow 'vec1' as mutable and is not declared as mutable.

[0:37] In this case, the problem is that vec1.push(88), where vec1 is immutable by default which means that we can't use the push() function on it. If we add mut to the beginning of vec1 like the Rust compiler says that we should, that our code compiles, we've now created vec1 as a mutable vector, such that we can push into it.

egghead
egghead
~ 2 hours ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today