Skip to content

Commit

Permalink
Simplify the example code for Clone (#2001)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
randomPoison authored Apr 19, 2024
1 parent bb44b1d commit 59d63a6
Showing 1 changed file with 16 additions and 13 deletions.
29 changes: 16 additions & 13 deletions src/memory-management/clone.md
Original file line number Diff line number Diff line change
Expand Up @@ -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>

0 comments on commit 59d63a6

Please sign in to comment.