Clone
Sometimes you want to make a copy of a value. The Clone trait accomplishes this.
1. ```
fn say_hello(name: String) {
```
2. ```
println!("Hello {name}")
```
3. ```
}
```
5. ```
fn main() {
```
6. ```
let name = String::from("Alice");
```
7. ```
say_hello(name.clone());
```
8. ```
say_hello(name);
```
9. ```
}
```
This slide should take about 2 minutes.
- The idea of
Cloneis to make it easy to spot where heap allocations are occurring. Look for.clone()and a few others likevec!orBox::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.
clonegenerally 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
cloneis user-defined, so it can perform custom cloning logic if needed.
