Module 2Ownership CoreLesson 2 of 924 min
Move Semantics
Assignment and function calls move non-Copy values; fix errors with clone or redesign.
Moves invalidate the old name
rust
fn main() {
let s1 = String::from("AAPL");
let s2 = s1; // s1 moved into s2
// println!("{s1}"); // error: borrow of moved value
println!("s2={s2}");
}Output
s2=AAPLCopy types skip moves
i32, f64, bool, char, and tuples/arrays of Copy types implement Copy:
rust
let x = 5;
let y = x; // both validFunctions take ownership
rust
fn eat(s: String) {
println!("{s}");
}
fn main() {
let t = String::from("X");
eat(t);
// t is gone — cannot use t here
}Output
XHow quants usually fix this
- Borrow (
&str/&String) if you only read - Clone if you truly need two owners (costs allocation)
- Return ownership back if the function should give it back
rust
fn tag(mut s: String) -> String {
s.push_str("-G1");
s
}Exercise
Observe a move, then fix with clone and with returning ownership.
Challenge
Rewrite make_label to take &str only (best style for this case).
Tips
- Compiler move errors are normal — read them carefully
- Prefer &str parameters for read-only text
- Clone is fine while learning; optimize later
Try it live
Move SemanticsRust 2021
Loading editor…
Output
Press Run to compile and execute.