How to work around these conflicting implementations?

⚓ Rust    📅 2026-05-20    👤 surdeus    👁️ 2      

surdeus

I'm trying to make an encoding into bytes & decoding from bytes trait, around Zerocopy's traits. The difference is that Zerocopy requires aligned types (and these was something impossible with unaligned features), but I have large data volumes, and alignment bytes will bloat it a good deal.

In my first implementation, I relied upon using same names for functions: read_from_io/write_to_io. This worked in straightforward implementations, and with macros, where in both cases I just had to output code like

fn write_to_io(...) -> ... {
    self.member1.write_to_io(...)?;
    self.member2.write_to_io(...)?;
}

Then I wanted something more abstract with blanket implementation, but turns out it's very hard, because impl ... for T conflicts with impl<T> ... for Option<T>.

trait Foreign: Sized {
	fn read_from_io(&self) -> Vec<u8>;
} // from external crate

trait MyTrait {
	fn read_from_io(&self) -> Vec<u8>;
}

impl<T: Foreign> MyTrait for T {
	// should call do_the_job
	fn read_from_io(&self) -> Vec<u8> { todo!() }
}

// Foreign isn't implemented for Option<T>. So I try implementing it.
impl<T: Foreign> MyTrait for Option<T> {
	fn read_from_io(&self) -> Vec<u8> { todo!() }
}

// conflicting implementations!
impl<T: MyTrait> MyTrait for Option<T> {
	fn read_from_io(&self) -> Vec<u8> { todo!() }
}

If I de-duplicate and remove the T: Something condition, then of course nothing of Zerocopy or my traits is available in the impl.

I thought of making separate traits, but then how do I call methods on them in generic code? In every way, there's a trait that has to be implemented separately for T of 2 different traits.

For example, if I want to implement write_to_io for specific tuples, (T,), (T, U), etc. I still have to implement this conversion as a trait, again both for T and Option<T>, and it's again conflicting implementation.

trait IntoData {
    type Data;
    fn into_data(&self) -> Self::Data;

Specialization isn't coming soon. So...

What I'm thinking of is to resort to the first approach, where I just made the same method names as in Zerocopy's traits, and relied on macros to write them for members.

Please suggest some workarounds if you have.

1 post - 1 participant

Read full topic

🏷️ Rust_feed