Victor Ermolaev
Victor Ermolaev

Reputation: 791

Using associated constant in a default trait implementation

I would like to accomplish the following

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

and then define a bunch of struct-s implementing the Trait with different constants. Such as

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

Unfortunately the former snippet does not compile. I can have both an associated constant and a default implementation, but seemingly I cannot use the const in the default implementation. Is this possible at all?

Upvotes: 9

Views: 1935

Answers (1)

mcarton
mcarton

Reputation: 30061

The constant does not belong to a specific instance, but to the type itself. You must use Self::CONST:

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

(Permalink to the playground)

Upvotes: 14

Related Questions