Values, Text and Callbacks · 14 min · free with an account

Copy, Clone and Cow

Lesson preview · about 30%

Ask which bytes are shared, copied or allocated before choosing an ownership conversion.

Core idea

Clone semantics depend on the type; Cow delays ownership conversion until an operation needs it.

Start with the idea

Copy permits implicit duplication of a value. Clone is an explicit operation whose cost and semantics depend on its implementation. Cloning an Rc or Arc normally creates another owner of the same allocation; cloning a String normally creates owned string storage. The word clone alone does not tell you which one happened.

Cow stores either borrowed or owned data behind one interface. A borrowed Cow<str> can read a caller’s string without making an owned String. Requesting mutable access through to_mut converts the borrowed form into owned storage when needed. The original borrowed string is not changed.

Keep learning, for free

The rest of this lesson is waiting for you.

Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 754 lessons and algorithm steps are included.

No payment details. Your account opens the complete Academy.

← All lessons in Rust Interview Prep