Rust ownership systém eliminuje celé kategorie bugů — use-after-free, double free, data races — v compile time.
Ownership pravidla¶
- Každá hodnota má právě jednoho ownera
- Když owner opustí scope, hodnota se uvolní
- Ownership se přesouvá (move) při přiřazení
Move a borrowing¶
fn main() { let s1 = String::from(“hello”); let s2 = s1; // s1 moved to s2, s1 už neplatí! // Borrowing — reference let s3 = String::from(“world”); let len = calculate_length(&s3); // Immutable borrow println!(“{s3} has length {len}”); // s3 stále platí // Mutable borrow let mut s4 = String::from(“hello”); change(&mut s4); } fn calculate_length(s: &String) -> usize { s.len() } fn change(s: &mut String) { s.push_str(” world”); }
Pravidla borrowing¶
- Libovolný počet immutable references (&T)
- NEBO jedna mutable reference (&mut T)
- Nikdy obojí současně
- Reference musí být validní (lifetimes)
Klíčový takeaway¶
Ownership = memory safety bez GC. Move, borrow (&), mutable borrow (&mut). Compiler je váš přítel.