Ownership and Borrowing
Ownership
Moving a String
Each heap value has one owner. Assigning a String moves ownership, so the original name can no longer be used.
Program
Play the program to watch s1 move into s2.
ownership_move.rs
Replay: real traced execution (multi-file project)
fn main() {
let s1 = String::from("hello");
let s2 = s1;
let len = s2.len();
println!("{s2} {len}");
}
s1 ← "hello", s2 ← "hello", len ← 5
1fn main() {2 let s→ "hello"1 = String::from("hello");3 let s→ "hello"2 = s1;4 let le→ 5n = s2.len();5 println!("{s2} {len}");6}outputhello 5
Watch the Move
s1starts as the owner of"hello".let s2 = s1;moves the string tos2.s2.len()works becauses2is now the owner.- Using
s1after the move would be the mistake to look for.
before move: s1 -> "hello"
after move: s2 -> "hello"
s1 is no longer usable
ownership
A `String` owns heap memory through a single binding.
move
`let s2 = s1` moves ownership; `s1` is no longer usable.
len
`s2.len()` returns the byte length of the string.
Exercise: ownership_move.rs
Move a String into a new owner, trigger the old-name error once, then fix the print to use the current owner