Suppose there is a trait, whose methods all only take a reference of self
, such as
trait Trait {
fn foo(&self) -> i32;
}
I'd like to have this trait implemented for both Option<T>
and Option<&T>
(as I can't always afford ownership), with a trivial implementation such as
impl<T: Trait> Trait for Option<T> {
fn foo(&self) -> i32 {
if let Some(inner) = self { return inner.foo(); }
0
}
}
impl<T: Trait> Trait for Option<&T> {
fn foo(&self) -> i32 {
if let Some(inner) = self { return inner.foo(); }
0
}
}
However, doing so produces the following error:
error[E0119]: conflicting implementations of trait `Trait` for type `std::option::Option<&_>`:
--> option.rs:12:1
|
5 | impl<T: Trait> Trait for Option<T> {
| ---------------------------------- first implementation here
...
12 | impl<T: Trait> Trait for Option<&T> {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `std::option::Option<&_>`
|
= note: downstream crates may implement trait `Trait` for type `&_`
Moreover, the implementations are literally the same. Is it possible to do this in a more compact way?