mirror of
https://github.com/google/comprehensive-rust.git
synced 2025-01-10 00:44:21 +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:
parent
bb44b1d7a8
commit
59d63a6e89
@ -8,26 +8,29 @@ Sometimes you _want_ to make a copy of a value. The `Clone` trait accomplishes
|
||||
this.
|
||||
|
||||
```rust,editable
|
||||
#[derive(Default)]
|
||||
struct Backends {
|
||||
hostnames: Vec<String>,
|
||||
weights: Vec<f64>,
|
||||
fn say_hello(name: String) {
|
||||
println!("Hello {name}")
|
||||
}
|
||||
|
||||
impl Backends {
|
||||
fn set_hostnames(&mut self, hostnames: &Vec<String>) {
|
||||
self.hostnames = hostnames.clone();
|
||||
self.weights = hostnames.iter().map(|_| 1.0).collect();
|
||||
}
|
||||
fn main() {
|
||||
let name = String::from("Alice");
|
||||
say_hello(name.clone());
|
||||
say_hello(name);
|
||||
}
|
||||
```
|
||||
|
||||
<details>
|
||||
|
||||
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`.
|
||||
- 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`.
|
||||
|
||||
It's common to "clone your way out" of problems with the borrow checker, and
|
||||
return later to try to optimize those clones away.
|
||||
- It's common to "clone your way out" of problems with the borrow checker, and
|
||||
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>
|
||||
|
Loading…
Reference in New Issue
Block a user