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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With