在默认特征实现中使用关联常量

Using associated constant in a default trait implementation

我想完成以下工作

trait Trait {
    const CONST: f64;
    fn fun(&self) -> f64 {
        1.0 + self.CONST
    }
}

然后定义一堆 struct-s 实现 Trait 不同的常量。 如

struct Struct {}
impl Trait for Struct {
    const CONST: f64 = 1.0;
}

不幸的是,前一个片段无法编译。我可以同时拥有关联常量和默认实现,但似乎我不能在默认实现中使用常量。 这可能吗?

常量不属于具体实例,而是属于类型本身。您必须使用 Self::CONST:

trait Trait {
    const CONST: f64;
    fn fun(&self) -> f64 {
        1.0 + Self::CONST
    }
}

(Permalink to the playground)