The Rule of 3
We'll cover the following...
There are three different ways to pass a value into a function: move it, pass by reference, and pass by mutable reference. We see this in method calls as self
, &self
, and &mut self
. This pattern of 3 appears in more places in Rust, including in iterators.
Let’s say we want to iterate over a Vec
, and then use it again. Perhaps we’d write some code like this:
Press + to interact
fn main() {let fibs = vec![1, 1, 2, 3, 5, 8, 13];for x in fibs {println!("{}", x);}println!("{:?}", fibs);}
Unfortunately, this is going to fail:
error[E0382]: borrow of moved value: `fibs`
-->
...Access this course and 1400+ top-rated courses and projects.