Ownership e borrowing
Rust References and Borrowing
Let a function use a value without taking it: & to read, &mut to change.
Cosa imparerai
- & and &mut
- Borrowing in function calls
- Many readers or one writer
Borrow → what it allows
length(&message)read onlyadd_exclamation(&mut message)can change itlet first = &messagemany readers are fineUse a value without owning it
A reference lets code use a value without owning it. This is called borrowing. &value borrows for reading and &mut value borrows for changing.
length only reads the text, so it takes &str and message can still be used afterwards. add_exclamation needs &mut String to change it. Rust allows many readers at once or one writer, but never both, which rules out data races at compile time.
Punti chiave
- &value borrows for reading.
- &mut value borrows for changing.
- Many readers or one writer, never both.
Esempio Rust eseguibile
main.rs
fn length(text: &str) -> usize {
text.len()
}
fn add_exclamation(text: &mut String) {
text.push('!');
}
fn main() {
let mut message = String::from("Borrow me");
let size = length(&message); // immutable borrow
println!("{message} has {size} bytes");
add_exclamation(&mut message); // mutable borrow
println!("{message}");
let first = &message;
let second = &message; // many readers are fine
println!("{first} {second}");
}
Borrow me has 9 bytes
Borrow me!
Borrow me! Borrow me!Esercitati
Apri l'esempio nel compilatore online, cambia un valore o aggiungi una riga e prova a prevedere l'output prima di eseguirlo. Poi rompi il codice di proposito e leggi il messaggio del compilatore.
Hai finito questa lezione?
Segnala come imparata per tenere traccia dei tuoi progressi.
I tuoi progressi sono salvati in questo browser Accedi per conservarli su ogni dispositivo.
Esercitati con una sfida
Usa ciò che questa lezione spiega per risolvere un problema reale. Ogni sfida gira nel browser, con test immediati e una revisione dell'IA.
- Sposta gli zeri Sposta ogni zero alla fine mantenendo l'ordine degli altri elementi. Facile
- Rendi un Array Non Decrescente Trova il numero minimo di incrementi necessari affinché ogni valore sia almeno pari al precedente. Facile