Several links from @kmdreko & @sudo are helpful.
I understand why s.to_lowercase().to_str()
does not compile but wondered why &s.to_lowercase()
does not have the same problem.
This is called Temporary lifetime extension, the doc says:
The temporary scopes for expressions in let statements are sometimes extended to the scope of the block containing the let statement. This is done when the usual temporary scope would be too small, based on certain syntactic rules. For example:
let x = &mut 0;
// Usually a temporary would be dropped by now, but the temporary for `0` lives
// to the end of the block.
println!("{}", x);
I find this special rule a bit arbitrary. Here's a related discussion on why it does not apply to temp.as_bytes()
which I resonate.
Surprisingly there's a RFC which seemed to want to make this more regular, but somehow is not applicable here.
This article explains why Temporary Lifetime Extension is desired in some cases.
I found this older rust references helpful with understanding temporary values as well, with a lot of examples.