The Rule of 3
Explore the Rule of 3 in Rust programming to understand how to pass values to functions and iterate over collections correctly. Learn the distinctions between moving values, borrowing immutably, and mutably borrowing using iterators, for loops, and method calls, enabling you to write efficient and error-free Rust code.
We'll cover the following...
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:
Unfortunately, this is going to fail:
error[E0382]: borrow of moved value: `fibs`
--> src/main.rs:8:22
|
2 | let fibs = vec![1, 1, 2, 3, 5, 8, 13];
| ---- move occurs because `fibs` has ...