Struggeling with &str

Hello everyone
I'm struggling to understand the lifetime of the &str from the context below. Since it's a reference to the data, doesn't the block of memory for the string slice get dropped at the end of the function and thus render the reference invalid? Sorry if this has already been asked, I'm very new to Rust (coming from C++ and C) and I wasn't exactly sure what to search before posting.

fn do_something() -> Result<u32, &str> { 
// do something return Ok(u32)
// error return Err("Oh no")

The reference here is to a string literal, which is baked into the executable and so lives for as long as the program is running. This is represented by the fact that it has type &'static str, where 'static is a special lifetime indicating that the thing referenced lives until the end of the program.

In the code you wrote, the Rust compiler will object because the lifetime of the &str isn't clear in the signature and it requires you to explicitly annotate it, but something like this compiles:

fn do_something() -> Result<u32, &'static str> { 
    Err("Oh no")

The 'static lifetime is discussed here in the Rust book, with string literals given as the main example.


In the contex here, you can only return references to string constants. Whenever you type a string literal, that compiles to a reference to an immutable global containing the string data.

If you tried to return a dynamically created string, it would fail to compile for the reasons you mentioned.


A general advice: if possible try to create a minimal example which you can feed to the rust compiler. The compiler's feedback usually gives some insights. Then, of course, asking here is a good idea.


Thank you! That makes more sense. Interesting that the example I followed was from The Rust book. Must be a little outdated.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.