A unnecessary lifetime mark

fn foo(x:&str,y:&str) ->&str{

As above code shown, the compiler will tell me to mark lifetime, but the output is unrelated to input. Maybe compiler should aware this according to analysis the function body.

That's not done intentionally. The outward-facing API of the function shouldn't depend on its implementation.

1 Like

To clarify a little on what H2CO3 said: it is a deliberate design decision to not use any information in the body of a function for understanding its signature. This means you do not need to see the body of something to understand its interface, and that ability is important to Rust's designers and many of its users (including me).


I think this is outlined exactly here: Lifetime Elision - The Rustonomicon.

For questions of requiring smart lifetime annotations, I'd always refer to this quote which everyone should bear in mind


The other comments here have been good about why the compiler doesn't look at the body.

I'll approach this from the other direction, and say that a function that ignores its inputs and returns a string constant is not at all the usual case. So I think it's good that it doesn't just work here, and that you have to mark the -> &'static visibly.

Having this compile temporarily while you have the stub body seems like it's just setting you up for failure later when you actually implement it and end up needing different lifetimes, since a change to the lifetime annotations can break your callers.


Fine. Thanks everyone.

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.