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.
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:
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.