We can create type-aliase as below:
type Kilometers = i32;
let x: i32 = 5;
let y: Kilometers = 5;
println!("x + y = {}", x + y);
and we can create new-type-idiom as below:
struct Kilometers(i32);
But with the new-type-idion, I could not implement operator-overloading, I tried this playground:
use std::ops::Add;
struct Kilometers(i32);
impl Add for i32 {
fn add(self, other: Kilometers) -> i32 {
self + other
}
}
fn main() {
let x: i32 = 5;
let y = Kilometers(5);
println!("x + y = {}", x + y);
}
But got the below error:
Compiling playground v0.0.1 (/playground)
error[E0119]: conflicting implementations of trait `std::ops::Add` for type `i32`:
--> src/main.rs:5:1
|
5 | impl Add for i32 {
| ^^^^^^^^^^^^^^^^
|
= note: conflicting implementation in crate `core`:
- impl std::ops::Add for i32;
error[E0117]: only traits defined in the current crate can be implemented for arbitrary types
--> src/main.rs:5:1
|
5 | impl Add for i32 {
| ^^^^^^^^^^^^^^^^ impl doesn't use types inside crate
|
= note: the impl does not reference any types defined in this crate
= note: define and implement a trait or new type instead
error: aborting due to 2 previous errors
Some errors occurred: E0117, E0119.
For more information about an error, try `rustc --explain E0117`.
error: Could not compile `playground`.
To learn more, run the command again with --verbose.