Ownership and borrowing
Every value has one owner; references let you borrow without taking ownership.
What you will be able to do
- Moving a value transfers ownership; the original binding can no longer be used.
- Borrow with & for reading and &mut for mutation.
- Keep borrows short so the compiler can prove safety.
In plain English
Ownership prevents use-after-free and double-free at compile time. A value can have many immutable references or one mutable reference, not both. The borrow checker is enforcing a rule about aliasing and mutation.
fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
if a.len() >= b.len() { a } else { b }
}
fn main() {
let title = String::from("Rust Foundations");
let borrowed = &title;
println!("{}", longest(borrowed, "Go"));
println!("{}", title);
}Your turn
EasyBorrow a string
Write a function that returns the length of a &str without taking ownership.
RUST · starter
fn length(value: String) -> usize {
value.len()
}Check your understanding before moving on.
Knowledge checkQuestion 1
How many mutable references can exist to a value at once?
Select an answer to continue
Study tools
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign inFinished reading?
Lock in what you just learned.
0%
Mark this lesson complete to save your place and move one step closer to the certificate.