diff --git a/src/memory-management/clone.md b/src/memory-management/clone.md index a10da95af0a..897c5b80f93 100644 --- a/src/memory-management/clone.md +++ b/src/memory-management/clone.md @@ -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, - weights: Vec, +fn say_hello(name: String) { + println!("Hello {name}") } -impl Backends { - fn set_hostnames(&mut self, hostnames: &Vec) { - 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); } ```
-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.