I'm not sure if what I'm trying to do is possible.
I want to implement a method on the types i8, i16, i32, i64, and i28.
I thought I could do this by relying on the Eq and Ord traits.
I can get the code below to work if it is not generic and just targets one of the integer types.
Maybe I'm close to a solution. Can you see where I'm going wrong?
use std::cmp::{Eq, Ord};
trait Days<T: Eq + Ord> {
fn days_from_now(self) -> String;
}
impl<T: Eq + Ord> Days<T> for T {
fn days_from_now(self) -> String {
let s = match self {
-1 => "yesterday",
0 => "today",
1 => "tomorrow",
_ => if self > 0 { "future" } else { "past" }
};
s.to_string()
}
}
fn main() {
let days: i32 = -1;
println!("{}", days.days_from_now()); // yesterday
println!("{}", 0.days_from_now()); // today
println!("{}", 1.days_from_now()); // tomorrow
println!("{}", 2.days_from_now()); // future
println!("{}", (-2).days_from_now()); // past
}
Errors:
Compiling playground v0.0.1 (/playground)
error[E0308]: mismatched types
--> src/main.rs:11:13
|
8 | impl<T: Eq> Days<T> for T {
| - this type parameter
9 | fn days_from_now(self) -> String {
10 | let s = match self {
| ---- this expression has type `T`
11 | -1 => "yesterday",
| ^^ expected type parameter `T`, found integer
|
= note: expected type parameter `T`
found type `{integer}`
error[E0308]: mismatched types
--> src/main.rs:12:13
|
8 | impl<T: Eq> Days<T> for T {
| - this type parameter
9 | fn days_from_now(self) -> String {
10 | let s = match self {
| ---- this expression has type `T`
11 | -1 => "yesterday",
12 | 0 => "today",
| ^ expected type parameter `T`, found integer
|
= note: expected type parameter `T`
found type `{integer}`
error[E0308]: mismatched types
--> src/main.rs:13:13
|
8 | impl<T: Eq> Days<T> for T {
| - this type parameter
9 | fn days_from_now(self) -> String {
10 | let s = match self {
| ---- this expression has type `T`
...
13 | 1 => "tomorrow",
| ^ expected type parameter `T`, found integer
|
= note: expected type parameter `T`
found type `{integer}`
error[E0369]: binary operation `>` cannot be applied to type `T`
--> src/main.rs:14:26
|
14 | _ => if self > 0 { "future" } else { "past" }
| ---- ^ - {integer}
| |
| T
|
help: consider further restricting this bound
|
8 | impl<T: Eq + std::cmp::PartialOrd> Days<T> for T {
| ^^^^^^^^^^^^^^^^^^^^^^
error: aborting due to 4 previous errors
Some errors have detailed explanations: E0308, E0369.
For more information about an error, try `rustc --explain E0308`.
error: could not compile `playground`
To learn more, run the command again with --verbose.