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?
It should be noted that systems typically have more than one time constant. However, it is very typical for a system to have its time constants far apart from each other, resulting in a separation between fast transient responses and the dominant response (which is the slowest one).
Time constants are everywhere. Since (almost) nothing happens instantaneously, but rather with a delay, processes are said to have time constants associated with them. In electrical systems, purely resistive circuits are static (not dynamic) as there are no energy storing elements. Resistors do not store energy but rather dissipate it.
If a procedure-level variable is declared with the Static keyword, the variable retains its value as long as code is running in any module. When all code has finished running, the variable loses its scope and its value.
Static classes and static members are useful because they do not require instances created for each new object. That means, they consume fewer resources and no duplication of the same class or member is needed in memory. Static members make code cleaner.
One might consider a constant that is a function:
trait Foo<'a> {
const BAR: fn(&Self) -> &'a str;
}
struct MyFoo<'a> {
x: &'a str,
}
impl<'a> Foo<'a> for MyFoo<'a> {
const BAR: fn(&Self) -> &'a str = my_bar;
}
fn my_bar<'a>(a: &MyFoo<'a>) -> &'a str {
&a.x
}
Right now, I can't think of how this would be more beneficial than a method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With