Borrowing
Use references to borrow values without taking ownership.
Borrowing
Use references to borrow values without taking ownership.
Difficulty
Beginner
Code
fn calculate_length(s: &String) -> usize {
s.len()
}
fn main() {
let s = String::from("hello");
let len = calculate_length(&s);
println!(""{}" has length {}", s, len);
}Explanation
References (&) borrow values without taking ownership. Multiple immutable borrows are allowed.
Key Concepts
- Read the code carefully and understand the data flow
- Try modifying the example to see how it changes behavior
- Run this code in the Rust Playground
Related Topics
Browse more examples in the ownership category to build a complete understanding of this topic.