如何为自定义显式生命期绑定关联常数?

问题描述 投票:1回答:1

我有一个特征,我想在其上具有关联的常量,其中该常数将是实现该特征的类型的一个切片。像这样的东西:

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版。

rust lifetime
1个回答
0
投票

在大多数情况下,您可能只想将'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。)

© www.soinside.com 2019 - 2024. All rights reserved.