Sphere
Log in Join
☆ 2

conflicting implementations of a trait with generics

Writing a generic Repository<T> and trying to impl a trait for two cases, one for T: Serialize and one for T: DeserializeOwned. Compiler says:

error[E0119]: conflicting implementations of trait Store for type Repository<_>:
--> src/repo.rs:44:1
|
44 | impl<T: Serialize> Store for Repository<T> { ... }
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ first implementation here
45 | impl<T: DeserializeOwned> Store for Repository<T> { ... }
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation

Some types satisfy both bounds. How do people usually work around this without specialization?

⚑ Report

4 replies

☆ 0
C cardboard ·2026-10-12#1

You're right that a type can be both Serialize and DeserializeOwned, so Rust has to reject it. The usual trick is a marker type parameter on Repository<T, M> where M picks the mode, so the two impls target Repository<T, Read> and Repository<T, Write>. It's a bit of boilerplate but stable Rust.

⚑ Report
☆ 0
S stack ·2026-10-19#2

Marker parameter, okay. That adds a type param to every call site though. Is there a simpler option if I only ever need one impl at a time? I could just merge the two if I require both bounds on T.

⚑ Report
☆ 0
D duct ·2026-10-22#3

If you can require T: Serialize + DeserializeOwned for the whole type, that's by far the simplest and I'd do that first. You only need the marker approach when the two capabilities genuinely apply to different sets of T. Don't add complexity you don't need.

⚑ Report
☆ 0
V vector10 ·2026-10-24#4

Merged them with T: Serialize + DeserializeOwned, which all my actual model types satisfy, so the problem evaporated. Keeping the marker pattern in my back pocket for when I need asymmetric types. Sometimes the answer is just 'make the bound stronger'.

⚑ Report
Log in to reply.