Is it possible to implement TryFrom with a generic type?
⚓ Rust 📅 2026-06-12 👤 surdeus 👁️ 2Is it possible to implement TryFrom<T> for a generic type T like this?
#[derive(Debug)]
struct A;
impl<T> TryFrom<T> for A {
type Error = Infallible;
fn try_from(_input: T) -> Result<Self, Self::Error> { Ok(A) }
}
Attempting to compile this as-is produces the following compile error:
error[E0119]: conflicting implementations of trait `TryFrom<_>` for type `A`
--> src/lib.rs:7:1
|
7 | impl<T> TryFrom<T> for A {
| ^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: conflicting implementation in crate `core`:
- impl<T, U> TryFrom<U> for T
where U: Into<T>;
My current understanding is that it's not possible to implement TryFrom<T> using a generic type parameter T like this because this impl means that for any and every type T that could possibly exist, TryFrom<T> is implemented for A. Some of these types T might also implement Into<A>and for those that do, an implementation of TryFrom<T> for A is already provided by the blanket impl defined in std: impl<T, U> TryFrom<U> for T where U: Into<T>.
Is this explanation correct? And if so, why isn't it possible to exclude all types T which might implement Into<A> using a trait bound like this?
trait MyTrait;
struct A;
impl<T: MyTrait> TryFrom<T> for A {
type Error = Infallible;
fn try_from(_input: T) -> Result<Self, Self::Error> { Ok(A) }
}
It seems to me that since MyTrait is a private trait, only types defined the same crate can implement it, and therefore impl<T: MyTrait> TryFrom<T> for A only applies to a finite set of types T which can all be proven not to implement Into<A> and therefore not introduce a trait impl conflict via the blanket impl. If this is not possible why not?
2 posts - 2 participants
🏷️ Rust_feed