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

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.