In this post, lets talk about references and lifetimes. For each value in Rust it could have a single owner and multiple references at a given point of time. The owner and reference are all variables in Rust. The Ownership System manages their validity during program runtime.
For the owners, they become unaccessible when out of scope or their ownership has been transferred to a new owner.
For the references, the Ownership System manages them using their lifetimes.
For simplicity, with owner its validity will be ended whenever its ownership is moved or transferred to another owner. With reference, its validity will be ended whenever its lifetime ends. A lifetime is the information about how long a reference is valid relative to its owner.
fn print_name(name: &str) {
println!("Your name is: {}", name);
}
fn main() {
let full_name = String::from("Alice Smith"); // the owner is `full_name` variable
let first_name_slice = &full_name[..5]; // Slice referencing first 5 characters
print_name(first_name_slice); // This is valid because the slice lifetime is shorter than the full_name lifetime
}
In the above snippet, the lifetime is implicit and inferred. Most of time you don't need to care about it. But there are cases you do. Sometimes, you need to indicate how long a reference should be valid.
Top comments (0)