capypad
0 day streak
rust / beginner
Snippet

Understanding Borrowing and References

Borrowing allows you to use values without taking ownership. By passing a reference `&`, the function borrows the value temporarily. The original owner `s1` remains valid after the function call. Rust enforces borrowing rules at compile time, preventing dangling references and data races.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
fn main() {
let s1 = String::from("Hello");
 
let len = calculate_length(&s1);
println!("The length of '{}' is {}.", s1, len);
}
 
fn calculate_length(s: &String) -> usize {
s.len()
}
Breakdown
1
let s1 = String::from("Hello");
Creates a String value owned by `s1`.
2
calculate_length(&s1)
Passes a reference to `s1`, not the value itself.
3
fn calculate_length(s: &String)
Parameter `s` borrows a String reference. The function does not own the data.
4
s.len()
Accesses the borrowed reference to get its length.