liveBook · Manning

Copy

As explained in Code Like a Pro in Rust

Clone is a standard Rust trait that defines how a value can produce a duplicate of itself.

Use `clone()` when you need a separate owned value while retaining the original. The method comes from Rust’s `Clone` trait. Assignment and borrowing are not substitutes for an explicit clone: borrowing gives access through a reference, while cloning creates another value. section 5.3

Keep an independent vector

```rust let mut cities = vec!["Chicago", "Houston"]; let saved = cities.clone(); cities.push("Phoenix"); assert_eq!(saved, vec!["Chicago", "Houston"]); ``` Cloning the vector preserves its earlier contents in `saved`; the later push changes only `cities`. section 5.3

For a struct whose fields implement `Clone`, `#[derive(Clone)]` supplies the implementation. A derived clone calls cloning recursively on its fields. Use it when duplication is intended, not merely to get around choosing between ownership and a reference. section 4.5.3 section 5.3

Before duplicating large or frequently processed values, check the operation’s signature:

  • `&self -> &str` generally returns borrowed data; `&self -> String` may allocate a new owned result. section 5.4
  • `&mut self` may update the existing value. For ASCII strings, `make_ascii_lowercase()` modifies in place, whereas `to_lowercase()` returns a new `String`. section 5.4
  • Do not assume `String -> String` avoids a copy just because it consumes its input: an implementation can still construct a new string. section 5.4

How Code Like a Pro in Rust covers it

How deep it goes
Demonstrates `clone()` and derived implementations, then gives signature-based copy heuristics; defers fuller trait treatment.
Examples
Uses a cloned vector modified after duplication, a struct deriving `Clone`, and string-lowercasing functions.
What it assumes
Assumes familiarity with Rust structs, references, and method calls; does not require implementing traits manually.
What you can do after
Apply Rust’s `clone()` and `#[derive(Clone)]` deliberately, and evaluate string APIs for unnecessary copies.
How it connects
Connects cloning to ownership, borrowing, references, derived traits, immutability, and in-place mutation.

Also explained in

Compare how 5 books explain copy →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Code Like a Pro in Rust. The section links point to the parts of the book it draws on.