
Recall first from The three ownership rules and moves
- Each value has exactly one owner at a time.
- When the current owner goes out of scope, Rust drops the value automatically.
- Moving a String transfers ownership of its existing heap buffer without duplicating its contents.
Which values copy on assignment?
3 min readYou just saw that moving a String transfers ownership. This lesson answers why an integer behaves differently: some types copy implicitly and others do not.
A Linux serial utility may need to retain a configured speed while it prepares a second set of settings. It may also keep a device label for its status display while preparing a modified label for a log entry. The Linux terminal interface exposes operations for reading and setting terminal attributes, including line speeds. The Rust examples below use ordinary program values for a speed and a label. They require no terminal access and perform no hardware I/O.
a Rust trait that lets the language duplicate a value implicitly when an operation such as assignment takes that value by value answers a question you can ask as you read a line of code. Will the source still be usable after this assignment? For let second = first; with a local variable first, look at the type of first. If it implements Copy, both bindings can be used afterward.
fn main() {
let configured_speed = 9_600_u32;
let mut candidate_speed = configured_speed;
candidate_speed += 1;
assert_eq!(configured_speed, 9_600);
assert_eq!(candidate_speed, 9_601);
}
The values here are arithmetic examples. The assignment gives candidate_speed the same numeric value as configured_speed. Adding one changes only the mutable binding. The first assertion reads the original binding after the assignment, which is precisely what the compiler would reject if that binding had been moved and had received no new value. The mut keyword controls whether the candidate can be changed. The Copy trait determines what happens when the initial value is assigned.
An implicit Copy is a bitwise copy of the value. It has no user-defined copy routine to call. That describes the language behavior, so you can predict which bindings remain usable without knowing what machine instructions the compiler emits. Integer types such as u8, i32, and usize implement Copy. So do bool and char. In code that reads serial settings, a number, a flag, and a single mode character can therefore each be assigned to another binding and still be read through the original binding.
Tuples and arrays apply the rule to their elements. A tuple such as (u32, bool, char) implements Copy because every element type does. A fixed-size array such as [u8; 3] implements Copy because u8 does. The same rule works when the types are nested. In [(u8, bool); 3], each tuple is Copy, so the whole array is Copy. In (u32, String), the String prevents the whole tuple from implementing Copy. For the same reason, [String; 3] is a non-Copy array.
fn main() {
let settings = (9_600_u32, true, 'N');
let saved_settings = settings;
assert_eq!(settings, saved_settings);
let bytes = [1_u8, 2, 3];
let mut candidate = bytes;
candidate[0] = 7;
assert_eq!(bytes[0], 1);
assert_eq!(candidate[0], 7);
}
Here the tuple can be read through both bindings, and the array change shows that each binding holds its own array value. The compiler decides whether an array is Copy from its type. Counting the elements or checking the current contents cannot change that decision. Even an empty String has type String, and a tuple containing that empty string still follows the move rule on plain assignment.
Derive Copy for your own type
2 min readSuppose the speed and retry flag belong together. A tuple containing the two values already implements Copy. A named struct gives the fields names such as speed and retry, which helps a reader understand an assignment without looking up the order of the tuple elements. Rust requires the struct author to opt in to Copy, even when the individual fields already implement it. The usual declaration for a simple value type is #[derive(Clone, Copy)] directly above the struct.
#[derive(Clone, Copy)]
struct PortSettings {
speed: u32,
retry: bool,
}
fn main() {
let configured = PortSettings {
speed: 9_600,
retry: false,
};
let mut candidate = configured;
candidate.retry = true;
assert_eq!(configured.speed, candidate.speed);
assert!(!configured.retry);
assert!(candidate.retry);
}
The derived Copy implementation makes the assignment behave like the one for the tuple. Rust also requires any type that implements Copy to implement Clone. In this example, deriving Clone gives PortSettings an explicit .clone() method as well. Deriving Copy is what enables implicit duplication in let mut candidate = configured;. If the attribute were #[derive(Clone)] alone, configured.clone() would still be available, but plain assignment would move the struct.
Every field must implement Copy for this derive to succeed. If you add label: String to PortSettings and leave #[derive(Clone, Copy)] in place, the compiler rejects the Copy derive. You can derive Clone on its own because u32, bool, and String all implement Clone. The derived clone duplicates the field values using their clone implementations, so the cloned struct receives its own copy of the label text as well.
The choice to derive Copy communicates how the struct is meant to be used. With the two scalar fields above, assignments can create independent settings that the program can change and compare. A field added later may make that behavior unavailable. For example, if a revision adds the owned label, code that used let saved = configured; and then read configured will need to either keep only the moved value or explicitly clone it. When reading a struct definition, check the derive before assuming the assignment will behave like it does for a tuple with the same fields.
Clone when you need another owned value
3 min reada Rust trait that provides an explicit .clone() method whose behavior is defined by the type is what lets you retain an original String and create another owned String from it. Plain assignment of a String moves it, so only the destination can use that value afterward. A clone leaves the original usable and returns a value you can assign to a second binding.
fn main() {
let label = String::from("serial");
let mut log_label = label.clone();
log_label.push_str("-test");
assert_eq!(label, "serial");
assert_eq!(log_label, "serial-test");
}
This is a deep copy of the string contents. The new String owns its own text, and appending to it leaves the original text intact. The original label is immutable, and log_label is mutable. Each binding has its own rule for whether it can change. The assertions check both the preservation of the original text and the result of modifying the clone. The examples use assertions to express expected behavior directly, so there is no terminal output to compare.
For a String, explicit cloning can allocate storage and copy the text bytes. That work matters in a serial utility that processes frequent messages or handles long labels. If the program needs to keep the source label and also edit a second owned label, the clone serves that requirement. If the program only needs the label under a different binding and has finished using the original binding, a move is sufficient. Decide which values need to remain usable after the line before choosing the operation.
The guarantee of an independent copy of the text comes from String's implementation of Clone. Other types can define cloning differently. A clone may share underlying data when the type is designed for sharing, while cloning an integer simply produces another integer with the same value. The .clone() spelling tells you the duplication is explicit. The type tells you what gets duplicated and what work the operation can require. For a Copy type such as u32, plain assignment already gives the same value to the destination and leaves the source usable.
When you review an assignment, ask what the source type is and whether later code needs to use the source. For the types in this lesson, Copy leaves the source available automatically, a move passes the existing value to the destination, and String::clone explicitly gives you two independently owned strings. The next lesson, String, the stack, and the heap, explains where a String stores its text and why moving it and cloning it involve different work.
Key takeaways
- Assignment implicitly copies a Copy value and leaves the source usable.
- A tuple or array implements Copy when all its elements implement Copy.
- A struct with Copy fields can opt in with #[derive(Clone, Copy)].
- Cloning a String duplicates its text, and other types define their own clone behavior.
Reflect
- Explain to a colleague, in two sentences: classify integers, booleans, characters, tuples, and arrays by whether they implement Copy.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Rust docsThe Rust Book: What is ownership? (Copy and Clone)
- Rust docsstd::marker::Copy
- Rust docsstd::clone::Clone
- Rust docsThe Rust Book, appendix C: derivable traits
Official documentation first. Links checked when the lesson was published.