January 2019
Beginner to intermediate
554 pages
13h 31m
English
Structs, enums, and traits definitions can also be provided with constant field members. They can be used in cases where you need to share a constant among them. Take, for example, a scenario where we have a Circle trait that's is meant to be implemented by different circular shape types. We can add a PI constant to the Circle trait, which can be shared by any type that has an area property and relies on value of PI for calculating the area:
// trait_constants.rstrait Circular { const PI: f64 = 3.14; fn area(&self) -> f64;}struct Circle { rad: f64}impl Circular for Circle { fn area(&self) -> f64 { Circle::PI * self.rad * self.rad }}fn main() { let c_one = Circle { rad: 4.2 }; let c_two = Circle { rad: ...Read now
Unlock full access