Move & Clone
Need a value in two places? Rust offers two doors: hand the ownership across, or explicitly duplicate the data.
Clone: Deep Copy
let s1 = String::from("hello");let s2 = s1.clone(); // deep copy of the heap data
println!("{}", s1); // OK: s1 still owns its copyprintln!("{}", s2); // OK: s2 owns a separate copyclone() allocates fresh heap and copies the bytes. The cost is visible in the source — no implicit deep copies sneaking in.
Copy: Stack-Only
Types that opt into the Copy trait duplicate themselves on assignment, no fuss:
let x: i32 = 42;let y = x; // copy, not moveprintln!("{} {}", x, y); // both validThe Copy club: every integer type, bool, f32/f64, char, plus tuples and fixed-size arrays whose elements are themselves Copy.
Copy versus Move is a semantics call, not just a performance one. Copy says: "this value is shallow enough that duplicating it is always cheap and always correct." Move says: "this value owns something — heap, file handle, lock — and silent duplication would be a bug."
Functions and Clone
If a function needs the value but you'd like to keep it around afterward, hand it a clone:
fn print_string(s: String) { println!("{}", s);}
let s = String::from("hello");print_string(s.clone()); // pass a cloneprintln!("{}", s); // s is still validIdiomatic Rust avoids the allocation altogether — you borrow instead. We get to that in the next module:
fn print_string(s: &String) { println!("{}", s);}
let s = String::from("hello");print_string(&s); // borrow, no clone neededprintln!("{}", s); // s is still validMoving Out of Collections
let v = vec![String::from("a"), String::from("b"), String::from("c")];
// This moves a single element out:let first = v.into_iter().next().unwrap();// v is no longer valid - into_iter() consumed it
// To keep the vector, use indexing with clone:let v2 = vec![String::from("a"), String::from("b")];let first = v2[0].clone(); // clone the elementprintln!("{}", first);println!("{:?}", v2); // v2 is still validWhat you can't write is let first = v[0]; for a String element. Indexing only borrows, so the compiler stops you with E0507 (cannot move out of index). The runner shows three ways round it.
Pattern: Return Ownership
A common workaround before borrowing clicks: return ownership back out:
fn process(s: String) -> String { println!("Processing: {}", s); s // return ownership back to caller}
let s = String::from("data");let s = process(s); // s moves in, then moves back outprintln!("{}", s); // s is valid againIt works, sure, but the ergonomics are awful. Borrowing — coming up next module — does this without the move-out-move-back dance.
Challenges
Demonstrate ownership by creating a String, moving it, and cloning it.