Hi!
I can't wrap my head around why the following code throws "Conflicting implementations of trait" error:
pub struct A;
pub trait Trait<T> {
fn do_something(input: T);
}
impl<T> Trait<T> for A
where
T: Add<T>,
{
fn do_something(input: T) {}
}
// Conflicting implementations of trait
impl<T> Trait<T> for A
where
T: Add<T> + Mul<T>,
{
fn do_something(input: T) {}
}
I would like to handle the two implementations differently, but I'm not sure how to go about it.
Any help would be appreciated
bjorn3
March 16, 2022, 8:13pm
2
This would require specialization which is an unstable feature.
Thanks @bjorn3 ! Is there any workaround for this?
bjorn3
March 16, 2022, 8:21pm
4
## Autoref-based stable specialization
"Specialization" refers to permitting overlapping impls in Rust's trait system
so long as for every possible type, one of the applicable impls is "more
specific" than the others for some intuitive but precisely defined notion of
specific. Discussions about a specialization language feature have been ongoing
for 4.5 years ([RFC 1210], [rust-lang/rust#31844]). Today the feature is
partially implemented in rustc but is not yet sound when mixed with lifetimes
([rust-lang/rust#40582]) and requires more language design work and compiler
work before it could be stabilized.
[RFC 1210]: https://github.com/rust-lang/rfcs/pull/1210
[rust-lang/rust#31844]: https://github.com/rust-lang/rust/issues/31844
[rust-lang/rust#40582]: https://github.com/rust-lang/rust/issues/40582
This page covers a stable, safe, generalizable technique for solving some of the
use cases that would otherwise be blocked on specialization.
The technique was originally developed for use by macros in the [Anyhow] crate.
This file has been truncated. show original
It doesn't work in generic contexts though. Only if the concrete type is known. Otherwise it will fallback to the most general implementation.
Hm interesting, thanks for sharing! For now I'll just have to duplicate for each concrete type, since I don't have many.
But I would be curious to learn why this specific case is considered "conflicting impl". How could Add and Add + Mul be conflicting, since one is strictly more specific than the other??
bjorn3
March 16, 2022, 9:11pm
6
For types implementing both Add and Mul both implementations apply and thus conflict with eachother. The whole point of specialization is to allow such conflicts if one implementation applies in a strict subset of another marked as specializable.
1 Like
system
Closed
June 14, 2022, 9:12pm
7
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.