borrowing
A function that needs a value does not always need to own it References let you use data without taking it
Immutable borrow
fn calculate_length(s: &str) -> usize {
s.len()
}
&str is a borrowed slice
The function can read
It cannot free the memory
The owner stays the owner
Mutable borrow
fn append(text: &mut String, suffix: &str) {
text.push_str(suffix);
}
Only one mutable borrow at a time While it exists, no other borrow of the same value is allowed That is how Rust prevents data races at compile time
The rule
- any number of immutable references
- or one mutable reference
- never both at the same time
Try to break it and the compiler points at the conflicting lines It is stricter than a code review and faster than a thread sanitizer
Dangling references
fn bad() -> &String {
let s = String::from("hello");
&s
}
That does not compile
s goes out of scope and the reference would point at freed memory
Rust rejects it before the program exists
Slices
A slice is a view into a sequence
&[T] borrows a slice of an array or vector
No copy, no ownership transfer
What this buys you
Shared read access is safe Exclusive write access is safe The combination is the race condition Rust makes that combination impossible to compile
Next
Structs and methods in 05 structs and methods
Posted