1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-06-08 10:36:17 +02:00

Simplify the example code for Clone (#2001)

The previous example code for the `Clone` slide was a bit too complex in
a way that obscured the fundamental point. I've replaced it with the
`say_hello` example from the previous slide, but updated to demonstrate
how cloning can address the borrow checker error. I also added a speaker
note to mention that `Clone` performs a deep copy, which might be
different from what students are used to if they come from a language
like Python that does shallow copies by default.
This commit is contained in:
Nicole L 2024-04-19 07:18:31 -07:00 committed by GitHub
parent bb44b1d7a8
commit 59d63a6e89
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -8,26 +8,29 @@ Sometimes you _want_ to make a copy of a value. The `Clone` trait accomplishes
this. this.
```rust,editable ```rust,editable
#[derive(Default)] fn say_hello(name: String) {
struct Backends { println!("Hello {name}")
hostnames: Vec<String>,
weights: Vec<f64>,
} }
impl Backends { fn main() {
fn set_hostnames(&mut self, hostnames: &Vec<String>) { let name = String::from("Alice");
self.hostnames = hostnames.clone(); say_hello(name.clone());
self.weights = hostnames.iter().map(|_| 1.0).collect(); say_hello(name);
}
} }
``` ```
<details> <details>
The idea of `Clone` is to make it easy to spot where heap allocations are - The idea of `Clone` is to make it easy to spot where heap allocations are
occurring. Look for `.clone()` and a few others like `Vec::new` or `Box::new`. occurring. Look for `.clone()` and a few others like `Vec::new` or `Box::new`.
It's common to "clone your way out" of problems with the borrow checker, and - It's common to "clone your way out" of problems with the borrow checker, and
return later to try to optimize those clones away. return later to try to optimize those clones away.
- `clone` generally performs a deep copy of the value, meaning that if you e.g.
clone an array, all of the elements of the array are cloned as well.
- The behavior for `clone` is user-defined, so it can perform custom cloning
logic if needed.
</details> </details>