Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Post History
As a relative newcomer to Rust, I'm trying to understand the behaviour of lifetimes, but I am confused by the following code: let s: &str = "first"; let mut r: &str = s; println!("First ...
#1: Initial revision
What allows a string slice (&str) to outlive its scope?
As a relative newcomer to Rust, I'm trying to understand the behaviour of lifetimes, but I am confused by the following code: let s: &str = "first"; let mut r: &str = s; println!("First ref is {}", r); { let inner: &str = "second"; r = inner; } println!("Second ref is {}", r); Since we are taking a long-lived reference `r` to a string slice `inner` which is destroyed at the end of its scope, I was expecting this code to fail to compile with a "variable does not live long enough" error. But to my surprise, it compiles fine, and prints valid output: First ref is first Second ref is second It seems that the reference `r` is somehow keeping the `"second"` string slice alive beyond the end of the scope in which it is defined, but I haven't seen anything in the book which mentions this. What am I missing?