Avoid unnecessary copies
Quick answer
Rust can move an owned value or borrow it without cloning its contents. Choosing the right ownership boundary can reduce allocation and copying while preserving clear lifetimes.
Borrow first, own when needed
Accept slices and str references for read-only access. Return borrowed views only while the original data remains valid. Cow can keep a borrowed value unchanged and allocate only when a transformation needs owned data. Reusing Vec capacity can reduce allocations, but clear does not guarantee freeing memory. Borrowing can extend lifetimes and retain a large backing allocation; measure actual trade-offs.
fn header(line: &str) -> Option<&str> { line.split_once(':').map(|(name, _)| name) }fn main() { println!("{:?}", header("kind:demo")); }Expected stdout (not executed):
Some("kind")The returned view refers to existing text rather than allocating a new String.
use std::borrow::Cow;fn label(s: &str) -> Cow<'_, str> { if s.contains('_') { Cow::Owned(s.replace('_', "-")) } else { Cow::Borrowed(s) }}fn main() { println!("{} {}", label("fast-path"), label("slow_path")); }Expected stdout (not executed):
fast-path slow-pathThe unchanged path keeps a borrowed value.
Common mistake
Do not add clone just to silence a borrow error without considering the lifetime design.
Try it yourself
Add tests that distinguish Cow::Borrowed from Cow::Owned and identify the lifetime constraint.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Avoid unnecessary copies — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
A tiny borrowed substring keeps a very large backing String alive. What trade-off should be considered?
Avoid unnecessary copies — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn header(line: &str) -> Option<&str> { line.split_once(':').map(|(name, _)| name) } fn main() { println!("{:?}", header("kind:demo")); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Avoid unnecessary copies — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust use std::borrow::Cow; fn label(s: &str) -> Cow<'_, str> { if s.contains('_') { Cow::Owned(s.replace('_', "-")) } else { Cow::Borrowed(s) } } fn main() { println!("{} {}", label("fast-path"), label("slow_path")); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.