Go to content
Web development

Rust Ownership: When to Move, Clone, or Reference

Rust’s ownership rules decide who can use a value and when. Every value has exactly one owner, a variable or data structure that holds it. When you pass a value to a function without a reference, you move it: the function becomes the new owner, and you cannot use the original binding again. A reference, written &T or &mut T, borrows the value temporarily so the function can read or mutate it without taking ownership. A clone, written .clone(), creates a new independent value, so you can keep using both the original and the copy.

When the compiler’s borrow checker rejects your code, you usually have three ways forward: borrow the value, move it, or clone it. Pick the cheapest fix that matches what the data actually needs. If the function only reads the value, borrow it. If the caller is done with the value, move it. If the value must stay alive in two places at once, clone it or share ownership with a reference-counted pointer such as Rc or Arc, which let multiple owners share one copy of the data. Cloning is not a failure. It is the right answer whenever the alternative is a contorted structure that fights the borrow checker for no performance gain.

Move, borrow, and copy: what each one does

Most types move by default. When you pass a String or a Vec to a function, the function owns it, and using the original afterward is a compile error. The function receives the allocation and the ownership bookkeeping without copying the data, so the call is cheap; the cost is that the caller loses the value.

Types that implement the Copy trait behave differently. Integers, floats, booleans, and characters are copied by default rather than moved, so you can keep using the original after passing it. Copy means an implicit bitwise copy of the memory region, and it only works for types that are plain bundles of copyable fields. You can make your own types Copy by deriving Copy and Clone, but you cannot make a type Copy if it implements the Drop trait, which runs cleanup code when a value goes out of scope. Dropping both the original and the copy would run that cleanup twice. Copy types in Rust covers the rules and the derivation.

References are temporary loans. &T lets any number of readers share the value; &mut T gives one exclusive writer. The borrow checker enforces the rule that you can have either many shared borrows or one mutable borrow at a time. Modern Rust uses non-lexical lifetimes, which end a borrow as soon as the code stops using it rather than at the end of the enclosing block, so you can reorder statements to resolve conflicts without changing the data flow.

When you call .clone(), the type’s Clone implementation produces a new value using the logic it defines. For a String or Vec, that means copying the heap data element by element. For a reference or a smart pointer, the new value may still point to the same underlying data. The Clone trait documentation notes that every type that implements Copy must also implement Clone, because Clone is a supertrait of Copy.

Clone costs depend on the type

A clone does not cost the same for every type, and misjudging it is the most common performance mistake. When you clone a Vec or String, the clone allocates new memory and copies every element or byte. When you clone an Rc or Arc, the clone increments a reference count, a counter that tracks how many owners share the data, and returns another pointer to the same data. The increment is cheap regardless of how large the data is. The forum discussion on cheap versus expensive clones makes the distinction concrete: the cost of a clone is not obvious from the call site.

Because of that difference, experienced Rust code often writes Rc::clone(&foo) instead of foo.clone() to signal that the clone touches the pointer, not the data. The call is the same either way; the longer form just makes the cheap operation readable.

One team building a Kafka-to-Postgres pipeline reported that overusing clone cost them 80% more memory, with profiling showing clone calls throughout the hot path. That is a single case study, not a universal law, but it shows what happens when large data gets deep-copied in a loop: memory and allocation work multiply.

Before you remove clones, profile. The strategy thread on removing unnecessary clones advises checking whether the code is fast enough and where time actually goes before optimizing. A quick way to find candidates is git grep ".clone()", which lists every call site in the repository.

Design the API around ownership

You decide between moving and borrowing in the function signature. If the function only reads the data, take &T. If it mutates the data in place, take &mut T. If it stores the data, turns it into a new owned value, or sends it to another thread, take T by value.

Taking by value is not a copy. When you move a String into a function, the function receives the allocation without copying it, so the call is cheap. The caller loses the value, which is the cost. If the caller does not need it afterward, moving is the cheapest option, and cloning would be pure waste.

A signature that borrows also widens the set of callers. A function that takes &str accepts a String, a &String, or a string literal; a function that takes String forces every caller to own a String and hand it over. The same logic applies to &[T], which accepts Vec<T>, arrays, and slices.

References are a temporary loan, and that limits where they can go. You cannot return a reference to data that will be dropped when the function returns, and you cannot store a reference in a struct that outlives the borrowed data. When you need to keep data alive beyond a borrow, you have to move it, clone it, or share it with Rc or Arc. The forum explanation of why clone exists frames this as a choice between ownership and borrowing.

A structural pattern that reduces clone pressure: define main structs that own data, then smaller structs that hold references to provide convenient views. The owner struct lives in one place, and the rest of the code borrows through the view structs. This is one of the strategies recommended for removing unnecessary clones.

When cloning is the simpler choice

Cloning is not wrong, and it cannot always be avoided. Sometimes you genuinely need two independent values: you need to keep the original and also hand a copy to another part of the program that will outlive any borrow. In that situation, a clone is the direct expression of the requirement, and a borrow would be a lie.

When you are unsure whether to borrow or clone, it is easier to err on the side of cloning. If you overuse references, you get frustrating compile errors; if you overuse cloning, the code compiles and you can improve it later. That advice comes from a long-running forum discussion on when to use clone, and it is aimed at typical application code. In a hot loop, the calculus changes; in ordinary code, a clone that happens once per request is noise.

The same thread advises beginners to stop trying to avoid clone so they can focus on learning the rest of Rust. The borrow checker fight is a distraction when you are still learning the language. Cloning is a perfectly fine thing to do when there is no simple, idiomatic, more efficient alternative.

If the clone is cheap, because the data is small or the type is a reference-counted pointer, clone and move on. If the clone is expensive and happens often, invest in a borrow or a restructure.

The least expensive fix for borrow-checker errors

When the compiler rejects your code, run through the same ladder: borrow if the data can live long enough, or move if the caller is done with the value. Clone only if neither works and the clone is cheap or off the hot path; restructure only when clones are in the hot path. You pick the fix based on the error, because each error names a different problem.

"Value used after move" means you moved a value into a function call and then tried to use the original. If you do not need the original afterward, the move is correct; delete the later use. If you do need it, pass a reference instead of the value, or clone before the call if the function needs ownership.

"Cannot borrow as mutable" means you are holding a shared borrow and trying to mutate the same data. You can usually fix it cheaply by reordering the code so the shared borrow ends before the mutation starts. If you need the value during the mutation, clone it.

"Cannot move out of borrowed content" means you have a reference and tried to move a field out of it. You can clone the field, borrow the field instead, or take ownership of the container if the caller can give it up.

Mutable borrow conflicts in loops happen when you iterate over a collection and mutate it or one of its fields inside the loop. You can collect the indices first and iterate over those, use retain for filtering, or iterate over indices instead of items. Struct method conflicts follow the same pattern: a method borrows the whole struct when you only need one field, so split the borrow by accessing fields directly or work through indices.

For cases where the borrow pattern is genuinely dynamic, RefCell provides interior mutability: it lets you mutate through a shared reference by moving the borrow check from compile time to runtime. It panics if you try to hold two mutable borrows at once, so it is a targeted tool, not a blanket escape hatch. The guide to fixing borrow checker issues collects these patterns with examples.

Two standard library tools resolve specific conflicts. The Entry API for maps solves the "check then insert" pattern, which otherwise needs two lookups and fights the borrow checker over the map’s borrow. Option::take and mem::replace let you move a value out of a mutable reference by leaving a placeholder behind, which is how you swap a field without cloning it.

Restructure when clones are the real problem

When profiling shows clones are the bottleneck, change the data structure instead of adding more borrow gymnastics. The main moves are borrow, move, box, share with Rc or Arc, use copy-on-write with Cow, or restructure the data flow.

If many parts of the program need the same large data, share it with Rc in single-threaded code or Arc when threads are involved. When you clone the pointer, only the counter increments, and the data is freed when the last owner drops. The discussion on Arc, Rc, and Clone in web development walks through when shared ownership beats copying.

For strings that repeat across the program, interning makes clones cheap. A single hash map from String to Rc<str> means each distinct string is stored once, and cloning the handle is a cheap non-atomic increment. This Stack Overflow answer on avoiding many string clones describes the tradeoff: you pay a lookup and manage the map’s lifetime, and you get near-free clones.

Cow (copy-on-write) lets a function accept either a borrowed or owned value and clone only when it needs to mutate. That fits APIs that sometimes transform their input and sometimes pass it through unchanged.

You pay for these changes in design time and complexity, so make them when the profile says the clone is the problem, not preemptively. A borrow that fits the data’s lifetime is always cheaper than a clone, but a clone that happens once is cheaper than a redesign.

More in Web development Back to top ↑