RFC 1623, stabilized in Rust 1.17.0, made it so that we do not have to explicitly specify the 'static
lifetime in a static
or const
:
const MY_DEFAULT_NAME: &str = "Anna";
// ^ Look, ma! No 'static!
RFC 195 defined associated constants, which were stabilized in Rust 1.20.0:
struct A;
impl A {
const B: i32 = 42;
}
When trying to combine these two, an error is raised:
struct A;
impl A {
const MY_DEFAULT_NAME: &str = "Anna";
}
error[E0106]: missing lifetime specifier
--> src/main.rs:4:28
|
4 | const MY_DEFAULT_NAME: &str = "Anna";
| ^ expected lifetime parameter
The related GitHub issue #38831 has a comment:
We decided against it because, in that case, there might be other lifetimes you would want. For example:
trait Foo<'a> { const T: &'a str; }
that said, revisiting this explanation, it feel a bit weak, since the value of an associated constant would still have to be all consisting of static data. So it seems like
'static
is a pretty good default if you don't say otherwise.
What is an example of an associated constant with a non-'static
lifetime? What benefit does providing a non-'static
lifetime bring?