I'm trying to get use of the new-type-idiom as below:
struct Kilometers(i32);
By creating the below playground that allow creating item in Kilometers then convert in to meters:
use std::ops::Mul;
struct Kilometers(i32);
struct Meters(i32);
pub trait Convert {
fn to_meter(self) -> Meters;
}
impl Convert for Kilometers {
fn to_meter(self) -> Meters {
self * 1_000.0
}
}
fn main() {
let x = Kilometers(5);
println!("{} Kilometers = {} Meters", x, x.to_meter());
}
But I got the below errors:
Compiling playground v0.0.1 (/playground)
warning: unused import: `std::ops::Mul`
--> src/main.rs:1:5
|
1 | use std::ops::Mul;
| ^^^^^^^^^^^^^
|
= note: #[warn(unused_imports)] on by default
error[E0369]: binary operation `*` cannot be applied to type `Kilometers`
--> src/main.rs:12:13
|
12 | self * 1_000.0
| ^^^^^^^^^^^^^^
|
= note: an implementation of `std::ops::Mul` might be missing for `Kilometers`
error[E0277]: `Kilometers` doesn't implement `std::fmt::Display`
--> src/main.rs:18:43
|
18 | println!("{} Kilometers = {} Meters", x, x.to_meter());
| ^ `Kilometers` cannot be formatted with the default formatter
|
= help: the trait `std::fmt::Display` is not implemented for `Kilometers`
= note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
= note: required by `std::fmt::Display::fmt`
error[E0277]: `Meters` doesn't implement `std::fmt::Display`
--> src/main.rs:18:46
|
18 | println!("{} Kilometers = {} Meters", x, x.to_meter());
| ^^^^^^^^^^^^ `Meters` cannot be formatted with the default formatter
|
= help: the trait `std::fmt::Display` is not implemented for `Meters`
= note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
= note: required by `std::fmt::Display::fmt`
error: aborting due to 3 previous errors
Some errors occurred: E0277, E0369.
For more information about an error, try `rustc --explain E0277`.
error: Could not compile `playground`.
To learn more, run the command again with --verbose.