Hi, I'm still rather a newbie to Rust. How can I have a default implementation of a trait function that can be overridden only if a generic type of the implementing type supports another trait?
trait Trait {
fn inc(&self);
fn rem(&self) {
println!("nope");
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct Foo<T> {
i: T,
}
impl<T> Trait for Foo<T>
where
T: Copy
+ Display
+ PartialEq
+ Add<u64, Output = T>,
{
fn inc(&self) {
println!("{}", self.i + 1);
}
}
/*
impl<T> Trait for Foo<T>
where
T: Copy
+ Display
+ PartialEq
+ Rem<u64, Output = u64>,
{
fn rem(&self) {
println!("{}", self.i % 2u64);
}
}
*/
fn main() {
let a = Foo { i: 1 };
a.inc();
a.rem();
}
I want to write the commented out code, but it doesn't compile (conflicting implementation). Alternatively, I can move fn rem to the other impl block, but that requires adding the Rem bound, which I don't want to do.
I want to use the default implementation from the trait if T doesn't support Rem, but if it does, I want to provide a different implementation. Suggestions?