Ownership und Borrowing
Rust References and Borrowing
Let a function use a value without taking it: & to read, &mut to change.
Das lernst du
- & 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.
Das Wichtigste
- &value borrows for reading.
- &mut value borrows for changing.
- Many readers or one writer, never both.
Ausführbares Rust-Beispiel
Rust
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!Üben
Öffne das Beispiel im Online-Compiler, ändere einen Wert oder füge eine Zeile hinzu und sage die Ausgabe voraus, bevor du es ausführst. Bring den Code danach absichtlich zum Scheitern und lies die Meldung des Compilers.
Lektion fertig?
Markiere sie als gelernt, um deinen Fortschritt zu verfolgen.
Dein Fortschritt ist in diesem Browser gespeichert Melde dich an, um ihn auf jedem Gerät zu behalten.
Mit einer Challenge üben
Nutze den Inhalt dieser Lektion, um ein echtes Problem zu lösen. Jede Challenge läuft im Browser, mit sofortigen Tests und einem KI-Review.
- Nullen verschieben Verschiebe alle Nullen ans Ende und erhalte die Reihenfolge der anderen Elemente. Einfach
- Ein Array nicht abnehmend machen Finde die minimale Anzahl an Erhöhungen, sodass jeder Wert mindestens so groß ist wie der vorherige. Einfach