Learning Rust: Ownership
Published at November 20, 2024 by Aulia Rahman
This is where Rust gets unique. Ownership rules are weird coming from any other language.
Core Rules
From rustlings move_semantics:
Three main rules clicked after some practice:
- Each value has one owner
- When owner goes out of scope, value is dropped
- Can only have one mutable reference OR many immutable references
References & Borrowing
References were tricky at first:
Key things about references:
- & means borrow
- &mut for mutable borrow
- Can't have mutable + immutable refs at same time
- References must be valid (no dangling)
Slice Type
String slices make more sense now:
They're just references to part of the string - no ownership.
Notes & Gotchas
Things to remember:
- Clone when you need a copy
- References prevent moves
- Watch scope of borrowed values
- String literals are &str slices
- Vec<T> follows same rules
Still need to practice:
- Lifetimes (coming up next)
- Complex ownership scenarios
- When to use Box<T>
Next: Structs and Methods