Testcase: unit clarification
A useful method of unit conversions can be examined by implementing Add
with a phantom type parameter. The Add trait is examined below:
1. // This construction would impose: `Self + RHS = Output`
2. // where RHS defaults to Self if not specified in the implementation.
3. pub trait Add<RHS = Self> {
4. type Output;
6. fn add(self, rhs: RHS) -> Self::Output;
7. }
9. // `Output` must be `T<U>` so that `T<U> + T<U> = T<U>`.
10. impl<U> Add for T<U> {
11. type Output = T<U>;
12. ...
13. }
The whole implementation:
1. use std::ops::Add;
2. use std::marker::PhantomData;
4. /// Create void enumerations to define unit types.
5. #[derive(Debug, Clone, Copy)]
6. enum Inch {}
7. #[derive(Debug, Clone, Copy)]
8. enum Mm {}
10. /// `Length` is a type with phantom type parameter `Unit`,
11. /// and is not generic over the length type (that is `f64`).
12. ///
13. /// `f64` already implements the `Clone` and `Copy` traits.
14. #[derive(Debug, Clone, Copy)]
15. struct Length<Unit>(f64, PhantomData<Unit>);
17. /// The `Add` trait defines the behavior of the `+` operator.
18. impl<Unit> Add for Length<Unit> {
19. type Output = Length<Unit>;
21. // add() returns a new `Length` struct containing the sum.
22. fn add(self, rhs: Length<Unit>) -> Length<Unit> {
23. // `+` calls the `Add` implementation for `f64`.
24. Length(self.0 + rhs.0, PhantomData)
25. }
26. }
28. fn main() {
29. // Specifies `one_foot` to have phantom type parameter `Inch`.
30. let one_foot: Length<Inch> = Length(12.0, PhantomData);
31. // `one_meter` has phantom type parameter `Mm`.
32. let one_meter: Length<Mm> = Length(1000.0, PhantomData);
34. // `+` calls the `add()` method we implemented for `Length<Unit>`.
35. //
36. // Since `Length` implements `Copy`, `add()` does not consume
37. // `one_foot` and `one_meter` but copies them into `self` and `rhs`.
38. let two_feet = one_foot + one_foot;
39. let two_meters = one_meter + one_meter;
41. // Addition works.
42. println!("one foot + one_foot = {:?} in", two_feet.0);
43. println!("one meter + one_meter = {:?} mm", two_meters.0);
45. // Nonsensical operations fail as they should:
46. // Compile-time Error: type mismatch.
47. //let one_feter = one_foot + one_meter;
48. }
See also:
Borrowing (&), Bounds (X: Y), enum, impl & self,
Overloading, ref, Traits (X for Y), and TupleStructs.
