Chooce video playback speed
speed:1
  1. 39
    Rustlings move_semantics1: Borrowing vectors as mutable
    55s

Rustlings move_semantics1: Borrowing vectors as mutable

InstructorChris Biscardi

Share this video with your friends

Send Tweet

README for this exercise.

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

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

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: 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 ).

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.

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.

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.