Files
rust-book-walkthrough/ownership/src/references_and_borrowing.rs
T
2026-10-05 18:08:41 +01:00

54 lines
1.7 KiB
Rust

pub fn run() {
println!("\n=== references and borrowing ===\n");
// We can provide a reference to a String value.
// A reference is like a pointer to an address in memory, which we can follow to access the data.
// The data itself is owned by some other variable.
// This is however not a pointer, because a reference guarantees to point at a valid value of a
// particular type for the life of the reference.
//
// Here is how you can use a variable as a reference to a parameter without taking ownership of
// it
// s is a reference to s1 which has a reference to an address in memory
let s1 = String::from("hello");
let len = calculate_length(&s1);
println!("The length of '{s1}' is {len}");
let mut str2 = String::from("hello");
change(&mut str2);
// At any given time, you can have either one mutable reference or any number of immutable references.
// References must always be valid.
}
fn calculate_length(s: &String) -> usize { // s is a reference to a string
s.len()
} // Here, s goes out of scope. But because s does not have ownership of what it refers to
// The String is not dropped.
// THE ACTION OF CREATING A REFERENCE IS **BORROWING**
// As it is in real life. You borrow something, and then you give it back. You do not own it.
// Here is an example that will not work
// fn main() {
// let s = String::from("Hello");
//
// change (&s);
// }
//
// fn change(some_string: &String) {
// some_string.push_str(", world")
// }
//
// A reference is by default also immutable. We are not allowed to modify something we have a
// reference to.
//
// MUTABLE REFERENCES
fn change(some_string: &mut String) {
some_string.push_str(", world!");
}