什么时候关联常量使用“static”以外的生命周期有用?
When is it useful for an associated constant to use a lifetime other than 'static?
RFC 1623,在 Rust 1.17.0 中稳定下来,这样我们就不必在 static
或 const
中明确指定 'static
生命周期:
const MY_DEFAULT_NAME: &str = "Anna";
// ^ Look, ma! No 'static!
RFC 195 定义了 相关常量,在 Rust 1.20.0 中得到稳定:
struct A;
impl A {
const B: i32 = 42;
}
尝试将这两者结合时,出现错误:
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
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.
具有非 'static
生命周期的关联常量的示例是什么?提供非'static
生命周期有什么好处?
人们可能会考虑作为函数的常量:
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
}
现在,我想不出这比方法更有用。
RFC 1623,在 Rust 1.17.0 中稳定下来,这样我们就不必在 static
或 const
中明确指定 'static
生命周期:
const MY_DEFAULT_NAME: &str = "Anna";
// ^ Look, ma! No 'static!
RFC 195 定义了 相关常量,在 Rust 1.20.0 中得到稳定:
struct A;
impl A {
const B: i32 = 42;
}
尝试将这两者结合时,出现错误:
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
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.
具有非 'static
生命周期的关联常量的示例是什么?提供非'static
生命周期有什么好处?
人们可能会考虑作为函数的常量:
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
}
现在,我想不出这比方法更有用。