I've tried to compile a program that contains this function, I was expecting it to not pass the compiler but it turns out it does and I'd like to know why so.
I'm currently learning Rust and recently I've encountered this function
fn test(input_str: &str) -> &str {
if input_str == "" {
let default: &str = "default";
&default
} else {
input_str
}
}
and as far as I know, we cannot return a reference to a variable allocated in the function as it does not live long enough, and I've tried to compile this function and it turns out that it passes the compilation successfully, I'd like to know why it does, my theory is that a hardcoded strings are treated somewhat differently and somehow they live as long as the main program but I don't know WHY so. So please can someone explain it to me clearly : ) and thnx.
The key here is that "default"
is not "variable allocated"1, it's a static string, or &'static str
in Rust parlance. This is because quoted strings are effectively "baked in" when your code is compiled, they're zero cost and always present. Nothing in this function requires allocation2.
There's no problem returning that. The same could not be said for &String
. Those need allocations that complicate their handling.
That being said, you could return a reference to an explicitly static
version of a String, but this requires a bit more preparation, not to mention tools like once_cell
or lazy_static
.
--
1 This is not really a thing. Variables don't allocate, but they can "own" something that is allocated.
2 Here meaning "dynamic allocation" as opposed to, say, stack space reservations.