我有一个特征,我想在其上具有关联的常量,其中该常数将是实现该特征的类型的一个切片。像这样的东西:
trait A: Sized {
const VALUES: &'static [Self];
}
#[derive(Debug)]
struct B {
b: u8,
}
impl A for B {
const VALUES: &'static [B] = &[B { b: 1 }];
}
#[derive(Debug)]
struct C {
c: usize,
}
impl A for C {
const VALUES: &'static [C] = &[C { c: 4 }];
}
fn main() {
println!("{:?}", B::VALUES);
println!("{:?}", C::VALUES);
}
这无法编译并显示错误:
error[E0310]: the parameter type `Self` may not live long enough
--> src/main.rs:2:5
|
2 | const VALUES: &'static [Self];
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= help: consider adding an explicit lifetime bound `Self: 'static`...
note: ...so that the reference type `&'static [Self]` does not outlive the data it points at
该寿命界限如何表示关联的常数?如果相关,我正在使用最新的rustc
稳定版(1.42.0
)和2018版。
在大多数情况下,您可能只想将'static
添加到绑定到A
的超特征中:
trait A: Sized + 'static {
const VALUES: &'static [Self];
}
您可以改为只将Self: 'static
绑定到VALUES
:
trait A: Sized {
const VALUES: &'static [Self] where Self: 'static;
}
这意味着您仍然可以为非A
类型实现'static
,但此类类型将没有与VALUES
相关联的常量,因此只有在特征A
具有其他特征时才这样做独立于VALUES
的有用属性。 (此外,为了在通用代码中使用T::VALUES
,您必须绑定T: A + 'static
而不是仅绑定T: A
。)