Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 681
Victor Ermolaev Avatar asked Nov 01 '19 18:11

Victor Ermolaev


1 Answers

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)

like image 106
mcarton Avatar answered Sep 25 '22 06:09

mcarton