struct A<'a> {
inner: &'a i32
}
impl core::ops::Deref for A {
type Target = i32;
fn deref(&self) -> &Self::Target{
&self.inner
}
}
fn main() {
let a: A = todo!();
}
Generates the following error:
Compiling playground v0.0.1 (/playground)
error[E0726]: implicit elided lifetime not allowed here
--> src/main.rs:5:27
|
5 | impl core::ops::Deref for A {
| ^ expected lifetime parameter
|
= note: assuming a `'static` lifetime...
help: indicate the anonymous lifetime
|
5 | impl core::ops::Deref for A<'_> {
| ++++
For more information about this error, try `rustc --explain E0726`.
error: could not compile `playground` due to previous error
What does the note "assuming a `'static` lifetime..." mean here? rustc --explain E0726 doesn't help much. The note would make sense to me if it was a warning for some old now-deprecated syntax but since it's an error I don't understand.
To be clear I understand why this doesn't compile, but I'm just confused at what the compiler is trying to tell me.
I think what it's trying to tell you is that you declared a type with an explicit lifetime, and now you're trying to implement a function for that type, but you didn't mention anything about this lifetime in the new functionality you're implementing. Rust assumes that lifetime doesn't matter, but it doesn't want to compile the program without being sure. If you change your impl core::ops::Deref for A to impl core::ops::Deref for A<'_> then it compiles with a warning about an unused variable.
From my limited understanding in The Book, I read that <'_> as saying 'there is a lifetime associated with the A struct that usually gets determined, but in this case we don't care about it`.
To be honest… no, looking through all the test cases among https://github.com/rust-lang/rust/pull/87244/files, I can’t find a single one where the “= note: assuming a `'static` lifetime...” note makes any sense to me.
Or is this to explain potential subsequent error messages because compilation goes on for a bit? Let’s see…
So it looks like the compiler does indeed make the syntactically erroneous impl Trait for Ref still generate a trait implementation, so that additional error messages can be generated, I presume, and for whatever weird reason it does indeed fall back to 'static for that. I mean, it’s weird… and very confusing in terms of error messages. Better than an ICE I suppose (here’s the issue this test case if from: https://github.com/rust-lang/rust/issues/80468), but still… Honestly, it should probably either treat the missing lifetime as elided, or consider the whole trait implementation too syntactically incorrect to consider at all; I don’t see how the status quo would be better than either of that.
Feel free to open an issue on GitHub about this, maybe someone wants to improve the situation.