Ownership and borrowing
Use compiler feedback to explain who owns a value and who may access it.
What you’ll learn
- Trace a move
- Distinguish an owned value from a borrow
- Explain why a reference needs a valid lifetime
Ask who owns the value
Ownership provides a way to reason about the responsibility for a value and its resources. Start with one owned string and follow what happens when it is passed to a function. A function parameter can receive ownership, which changes what the caller may subsequently use. Some types support copying, so do not turn one observed assignment into a rule that every value behaves identically. Read the type and the compiler diagnostic before deciding whether a move or a copy occurred.
Borrow for temporary access
A reference lets another part of a program access a value without transferring ownership. Use a shared borrow when inspection is enough, and request mutable access only when the operation needs to change the value. The language checks rules governing access and validity. Those rules are easier to understand through a small function contract than through a slogan about pointers. Ask whether the function needs to keep the value, only inspect it, or modify it for the caller.
Trace a useful function boundary
Imagine a function that measures a title. It can take a string slice and return a length, leaving the caller free to keep using its owned title. A different function that stores the title in a long-lived collection may need ownership instead. These are distinct API choices. They communicate responsibility and can affect copying or allocation. Choose the form that matches the operation, then check that each call site has the required access.
fn title_length(title: &str) -> usize {
title.len()
}
fn main() {
let title = String::from("Rivers");
println!("{}", title_length(&title));
println!("{}", title);
}
// len() counts bytes in this UTF-8 string.References cannot outlive their data
A reference must remain valid for the period in which it is used. Returning a reference to a temporary local allocation would leave the caller pointing at data that no longer exists, so the compiler rejects such designs. Lifetime annotations describe relationships needed by a contract; they do not create extra storage or make an object live forever. Often the clearer fix is to return an owned value or borrow from an input whose lifetime is appropriate.
Learn from a minimal compiler example
When a borrow error appears, reduce the example to the value, the borrow, and the conflicting use. Identify the last place each borrow is needed rather than inserting copies automatically. A clone can be correct when independent ownership is actually desired, but it should be a design choice. Test the public behavior after the code compiles: memory-safety checks do not establish that a parser accepts the right language or that a service returns the intended business result.
Try it yourself
A function only needs to inspect a title. What should you consider before taking ownership of the caller’s String?
Show a possible solution
Consider accepting a shared string slice, such as &str, so the caller retains ownership. Take ownership when the function needs to retain or independently own the value.
Check your understanding
Try 11 questions across rust. Read each explanation and revisit anything that needs another pass.
Practise this subjectGo to the source
Use these primary references to check details and explore the topic further.
Saved in this browser. Signed-in progress syncs to your account.