Zeeshan Adil
Book a call
← Rust for C# Engineers: From Garbage Collection to Ownership and Lifetimes

Chapter 7 of 16 · Part II, Working knowledge

Traits are interfaces that do not own your types

by Zeeshan AdilUpdated 30 min read
Listen to this articleRust Traits vs C# Interfaces and Extension Methods 30 min · read by an AI voice
0:00 / 29:36

How Rust traits differ from C# interfaces: implementing them for types you do not own, the orphan rule, newtypes, associated types and blanket impls.

Use your knowledge of C# interfaces as a starting point. By the end, you should be able to decide where an implementation belongs and recognize when a wrapper type is needed. Start with implementations and the orphan rule, then return to associated types and blanket implementations as you encounter them.

A trait describes behavior a type can implement. It can include methods, associated types, and constants. If you know C# interfaces, start there, then look at where Rust allows the implementation to live.

Code
trait HealthCheck {
    fn is_healthy(&self) -> bool;

    fn status_line(&self) -> String {
        if self.is_healthy() { "OK".to_string() } else { "DEGRADED".to_string() }
    }
}

The default method body is C# 8 default interface methods, and it works roughly the same way: implementors get it for free and may override it.

The difference is where the implementation goes.

Code
struct Database { connected: bool }

impl HealthCheck for Database {
    fn is_healthy(&self) -> bool { self.connected }
}

The impl block is separate from the type declaration, and it does not have to be in the same file, the same module, or written by the same person. That is the change that matters, and it is bigger than it looks. You can implement your trait for a type you did not write.

The thing extension methods cannot do

In C#, a type's interface list lives in the type's own declaration. Spread it across partial files if you like, but it is fixed by the assembly that defines the type, and it is baked into the metadata the compiler emits for it. Anyone downstream who wants that type to satisfy a new interface has to wrap it.

Rust has no such list. An impl is a free-standing item, and when the compiler checks whether a type satisfies a bound it considers every impl in the crate graph, wherever it was written. So this is legal:

Code
impl HealthCheck for i32 {
    fn is_healthy(&self) -> bool { *self == 200 }
}

That is an implementation of your interface for a primitive, with dispatch, with generic bounds, with everything an interface gives you.

Extension methods are the reflex you will reach for, and they do not reach. An extension method is a static method plus call-site sugar. It gives you the dot, and nothing else. Watch what happens when the dot is not the point:

Code
using System;
using System.Collections.Generic;

public interface IHealthCheck
{
    bool IsHealthy();
}

public static class IntExtensions
{
    public static bool IsHealthy(this int status) => status == 200;
}

public static class Program
{
    static void ReportAll<T>(IEnumerable<T> items) where T : IHealthCheck
    {
        foreach (var i in items) Console.WriteLine(i.IsHealthy());
    }

    public static void Main() => ReportAll(new[] { 200, 500 });
}

The call in Main does not compile, and the compiler says exactly why:

Code
error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic
type or method 'Program.ReportAll<T>(IEnumerable<T>)'. There is no boxing
conversion from 'int' to 'IHealthCheck'.

The extension method exists. 200.IsHealthy() compiles fine on its own. It just is not part of what int is, so it cannot satisfy a constraint, cannot be found through a T, and cannot be dispatched through an interface reference. In Rust the equivalent generic function takes i32 without comment, because impl HealthCheck for i32 did change what i32 is, from the compiler's point of view, for the whole crate graph.

This is why C# codebases grow adapter classes in places where Rust writes four lines. It is also why C# needs IEqualityComparer<T> and IComparer<T> as separate objects you pass around: when you cannot change how a foreign type compares, you have to smuggle the comparison in through a parameter. Rust has that escape hatch too, in the form of sort_by_key and friends, but it needs it far less often.

Trait methods exist only if the trait is in scope

There is a catch that trips up everyone arriving from C#, and it is the same catch extension methods have.

Code
mod health {
    pub trait HealthCheck {
        fn is_healthy(&self) -> bool;
    }

    impl HealthCheck for i32 {
        fn is_healthy(&self) -> bool { *self == 200 }
    }
}

fn main() {
    let status: i32 = 200;
    println!("{}", status.is_healthy());
}
Code
error[E0599]: no method named `is_healthy` found for type `i32` in the current scope
  --> src/main.rs:13:27
   |
3  |         fn is_healthy(&self) -> bool;
   |            ---------- the method is available for `i32` here
...
13 |     println!("{}", status.is_healthy());
   |                           ^^^^^^^^^^ method not found in `i32`
   |
   = help: items from traits can only be used if the trait is in scope
help: trait `HealthCheck` which provides `is_healthy` is implemented but not in scope; perhaps you want to import it
   |
1  + use crate::health::HealthCheck;
   |

The impl exists. The compiler can see it. It refuses anyway, because method resolution starts from the set of traits you have imported, and you imported none. Add use crate::health::HealthCheck; and it compiles.

The reason is the same one that makes the whole feature work. If a method call searched every trait in the dependency graph, then any crate anywhere could change the meaning of your code by adding an impl. Scoping the search to your imports means adding an impl in a library cannot silently hijack a call in a consumer.

Two related details, since you will hit both. Inherent methods, the ones in a plain impl Type block, win over trait methods with the same name, with no ambiguity error. And when two traits both provide a name method, you disambiguate with fully qualified syntax:

Code
trait Pilot  { fn name(&self) -> String; }
trait Wizard { fn name(&self) -> String; }

struct Human;

impl Human {
    fn name(&self) -> String { "just a person".to_string() }
}

impl Pilot for Human {
    fn name(&self) -> String { "Captain".to_string() }
}

impl Wizard for Human {
    fn name(&self) -> String { "Gandalf".to_string() }
}

fn main() {
    let h = Human;
    println!("{}", h.name());                    // just a person, inherent wins
    println!("{}", Pilot::name(&h));             // Captain
    println!("{}", <Human as Wizard>::name(&h)); // Gandalf
}

That is C#'s explicit interface implementation, solved from the call site instead of the declaration.

The orphan rule, and why it exists

You cannot implement someone else's trait for someone else's type. Try to format a Vec of String the way you want:

Code
use std::fmt;

impl fmt::Display for Vec<String> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "[{}]", self.join(", "))
    }
}
Code
error[E0117]: only traits defined in the current crate can be implemented for types defined outside of the crate
 --> src/main.rs:3:1
  |
3 | impl fmt::Display for Vec<String> {
  | ^^^^^^^^^^^^^^^^^^^^^^-----------
  | |                     |
  | |                     `Vec` is not defined in the current crate
  | impl doesn't use only types from inside the current crate
  |
  = note: define and implement a trait or new type instead

Niko Matsakis wrote the post that explains the design, and the case it protects is two "cousin" crates: neither depends on the other, both depend on std, and both want impl Display for Vec<String>. Each compiles alone. Link them and you have two answers to the same question. The rule as later refined in RFC 2451 and stated in the Reference is stricter than the folk version, but the folk version gets you most of the way: either the trait or the self type must be yours.

The folk version is a simplification, though. Watch this compile:

Code
use std::ops::Add;

#[derive(Debug, Clone, Copy)]
struct Bytes(u64);

impl Add<Bytes> for u64 {
    type Output = Bytes;
    fn add(self, rhs: Bytes) -> Bytes { Bytes(self + rhs.0) }
}

fn main() {
    println!("{:?}", 64u64 + Bytes(1024)); // Bytes(1088)
}

Add is foreign. u64 is foreign. It is still allowed, because the real rule looks at every type in the impl header, not only the self type. RFC 2451 phrases it as an ordered list: the self type first, then the trait's type arguments left to right. Somewhere in that list there must be a local type, and no uncovered generic parameter may appear before it. Here the list is u64, then Bytes, there are no generic parameters at all, and Bytes is local, so the impl is accepted. That is why you can teach u64 to add itself to your type without owning u64.

Newtype, and what it costs

When the orphan rule does block you, the standard move is to wrap the foreign type in a one-field struct. The community calls this a newtype, and it is the same idea as a C# adapter class, except mandatory and cheap.

Code
use std::fmt;

struct Csv(Vec<String>);

impl fmt::Display for Csv {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0.join(","))
    }
}

fn main() {
    let cols = Csv(vec!["region".to_string(), "p99".to_string(), "errors".to_string()]);
    println!("{cols}");           // region,p99,errors
    println!("{}", cols.0.len()); // 3
}

A one-field newtype often has no additional storage or runtime cost after optimization, but measure the actual workload. If you need a layout and ABI guarantee rather than relying on a particular compiler's behavior, #[repr(transparent)] makes it a guarantee about layout and ABI. The default representation deliberately promises less, so do not build unsafe code on the assumption without the attribute.

What a newtype is not free of is API surface. Csv has none of Vec's methods. You either reach through .0, forward the methods you need by hand, or implement Deref to the inner type, which the book suggests and which I would use sparingly, because Deref on a newtype leaks every inner method back out and undoes most of the reason you wrapped it.

Default methods carry more weight here than in C#

Two differences from default interface methods, and the second one is the interesting one.

First, a Rust default trait method can be called on a concrete value when the trait is in scope. A C# default interface method is not normally found as a member on the concrete class. This surprises people:

Code
public interface IHealthCheck
{
    bool IsHealthy();
    string StatusLine() => IsHealthy() ? "OK" : "DEGRADED";   // default implementation
}

public class Database : IHealthCheck
{
    public int OpenConns { get; init; }
    public int MaxConns { get; init; }
    public bool IsHealthy() => OpenConns < MaxConns;
}

public static class Program
{
    public static void Main()
    {
        var db = new Database { OpenConns = 95, MaxConns = 100 };
        Console.WriteLine(db.StatusLine());
    }
}
Code
error CS1061: 'Database' does not contain a definition for 'StatusLine' and no
accessible extension method 'StatusLine' accepting a first argument of type
'Database' could be found

You have to cast to the interface, or reach it through a constrained type parameter. The reason is C#'s member lookup rules: a default implementation is a member of the interface, not of the class, so it never enters the class's member set and never becomes a candidate for db.StatusLine(). In Rust, trait methods are found through the trait rather than through a member list, so db.status_line() resolves as long as HealthCheck is in scope.

Second, and much more consequential: because a default method sits on the trait, an implementor can override it, and every generic caller picks up the override statically.

Iterator is the example. The standard library trait has one required associated type, Item, one required method, next, and more than seventy provided methods with default bodies. Write next and you have map, filter, zip, take_while, fold, sum, collect, all of it:

Code
struct Countdown { remaining: u32 }

impl Iterator for Countdown {
    type Item = u32;

    fn next(&mut self) -> Option<u32> {
        if self.remaining == 0 {
            None
        } else {
            self.remaining -= 1;
            Some(self.remaining + 1)
        }
    }
}

fn main() {
    let total: u32 = Countdown { remaining: 5 }
        .filter(|n| n % 2 == 1)
        .map(|n| n * 10)
        .sum();
    println!("{total}");          // 90
}

C# gets the same adapters on IEnumerable<T>, but through LINQ's extension methods, which cannot be overridden by an implementor. So when Enumerable.Count wants to avoid walking a sequence it already knows the length of, it has nowhere to look except the object itself. The actual source does a chain of runtime type tests: is it an ICollection<TSource>, is it an internal Iterator<TSource>, is it a non-generic ICollection, and only then does it loop.

In Rust that fast path is a method override. Implement size_hint accurately and collect into a Vec reserves from the lower bound instead of growing. Override count or nth and every caller in every crate picks it up, resolved at compile time, with no type test. Small design decision, long tail, and one of the few places where Rust's model is straightforwardly better rather than differently balanced.

The cost shows up in versioning. Adding a defaulted method to a published trait can break downstream code when a consumer uses both your trait and another trait with a conflicting method name and the call becomes ambiguous. The Cargo SemVer reference documents this as a minor-but-possibly-breaking change. C# has the same hazard with default interface methods, which is part of why the feature arrived with such careful rules.

Supertraits are constraints, not base classes

Traits can require other traits, which reads like inheritance and is not:

Code
use std::time::Duration;

trait Monitored: HealthCheck {
    fn interval(&self) -> Duration;

    fn schedule_line(&self) -> String {
        format!("{}  (every {:?})", self.status_line(), self.interval())
    }
}

That says any type implementing Monitored must also implement HealthCheck. Read it as the bound it desugars to, where Self: HealthCheck. It buys Monitored's default bodies the right to call HealthCheck methods on self, and it buys callers the right to treat any Monitored as a HealthCheck. It is a constraint on implementors, not a base type. Nothing is inherited: no fields, no constructor, no base call, no slot layout.

If you write impl Monitored for Database without an impl HealthCheck for Database somewhere, the compiler tells you the bound is unsatisfied. That is the whole feature.

There is no inheritance

Rust has no class inheritance at all. No base classes, no virtual and override, no protected members.

For a lot of C# code this is a non-event, because the useful part of the hierarchy was the interface anyway. Where it bites is the places you leaned on a base class for something other than a contract, and each of those has a different answer.

Shared state in an abstract base. Composition. Put the shared struct in a field, and if callers need to reach it generically, add a trait method that hands out a reference to it.

Code
struct Common { name: String, last_checked: u64 }

trait HasCommon {
    fn common(&self) -> &Common;
    fn name(&self) -> &str { &self.common().name }
}

Verbose compared to a protected field. Also explicit about who owns what, which the rest of the language is going to force on you regardless.

The template method pattern. Rust does this with less ceremony and no loss. An abstract base with a non-virtual public method calling protected abstract hooks is, exactly, a trait with a defaulted method calling required methods. The status_line above is that pattern.

A polymorphic collection of subclasses. If the set of types is closed and you own it, an enum is usually the better answer, and gives you exhaustive match on top. If the set is open, you want a trait object, which the next section covers.

Reuse with no polymorphism. If the base class existed only so three types could share an implementation, write a free function and call it from three places.

Runtime discovery needs a different design. Rust does not have .NET's built-in reflection model, so a handler registry may be assembled explicitly or generated at build time. Dynamic libraries and plugin frameworks are also possible, but their interfaces and deployment constraints need care. More on that at the end of the section.

Associated types versus generic parameters

Iterator could have been written two ways. The standard library chose this:

Code
pub trait Iterator {
    type Item;
    fn next(&mut self) -> Option<Self::Item>;
}

The alternative would have been trait Iterator<T> with fn next(&mut self) -> Option<T>. The book walks through why not, and the difference is exactly one thing: how many times a type may implement the trait.

A generic trait can be implemented many times for one type, once per set of type arguments. An associated type can be chosen only once per type, because there can be only one impl Iterator for Countdown.

You already know what the other choice looks like, because C# made it. IEnumerable<T> is generic, so one class can implement it more than once:

Code
public class Both : IEnumerable<int>, IEnumerable<string>
{
    IEnumerator<int> IEnumerable<int>.GetEnumerator()    { yield return 1; }
    IEnumerator<string> IEnumerable<string>.GetEnumerator() { yield return "one"; }
    IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable<int>)this).GetEnumerator();
}

That compiles and runs. The cost lands on every call site. foreach (var x in b) is CS1640, because the type implements multiple instantiations of IEnumerable<T>, and you have to write foreach (var x in (IEnumerable<int>)b) to say which one you meant.

Rust's version of that class does not exist. Two impl Iterator for Countdown blocks give you:

Code
error[E0119]: conflicting implementations of trait `Iterator` for type `Countdown`
  --> src/main.rs:18:1
   |
5  | impl Iterator for Countdown {
   | --------------------------- first implementation here
...
18 | impl Iterator for Countdown {
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `Countdown`

In exchange, countdown.next() never needs an annotation, and neither does anything downstream of it. Every adapter in the chain can name Self::Item and the compiler knows what it is.

So the choice, when you are designing a trait. If the implementor decides the type, use an associated type. If the caller decides, use a generic parameter. An iterator's element type is a property of the iterator, so Item is associated. A conversion's source type is a property of the call, so From<T> is generic, and one type happily implements From<u32>, From<String> and From<io::Error> all at once.

Add shows both in one trait, which is a useful thing to have seen:

Code
pub trait Add<Rhs = Self> {
    type Output;
    fn add(self, rhs: Rhs) -> Self::Output;
}

Rhs is a generic parameter with a default, so you may implement Add for your type more than once, once per right-hand side. Output is associated, because once Self and Rhs are fixed, the result type is not a free choice.

The cost of picking wrong is asymmetric. Turning a generic parameter into an associated type breaks anyone who wrote two impls, and there may be nobody in that position. Turning an associated type into a generic parameter breaks every bound spelled Trait<Item = X> in every downstream crate, and unless you give the new parameter a default it breaks every bare mention of the trait as well. When in doubt, associated type, and take the pain later if it comes.

Operator overloading

Operators are traits in std::ops. + is Add, [] is Index, * on a smart pointer is Deref. Arithmetic on the primitives is still compiler-level, but for every other type the operator is a trait impl and nothing more.

Code
use std::ops::Add;

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
struct Bytes(u64);

impl Add for Bytes {
    type Output = Bytes;
    fn add(self, rhs: Bytes) -> Bytes { Bytes(self.0 + rhs.0) }
}

impl Add<u64> for Bytes {
    type Output = Bytes;
    fn add(self, rhs: u64) -> Bytes { Bytes(self.0 + rhs) }
}

impl Add<Bytes> for u64 {
    type Output = Bytes;
    fn add(self, rhs: Bytes) -> Bytes { Bytes(self + rhs.0) }
}

fn main() {
    println!("{:?}", Bytes(1024) + Bytes(512)); // Bytes(1536)
    println!("{:?}", Bytes(1024) + 64u64);      // Bytes(1088)
    println!("{:?}", 64u64 + Bytes(1024));      // Bytes(1088)

    let mut v = vec![Bytes(3), Bytes(1), Bytes(2)];
    v.sort();
    println!("{v:?}");                          // [Bytes(1), Bytes(2), Bytes(3)]
}

C# is closer here than people expect. An operator is a public static member declared inside one of its operand types, and at least one operand must be that type, so public static Bytes operator +(ulong left, Bytes right) declared inside Bytes is legal and always has been. 64UL + myBytes compiles. The requirement is the same shape as coherence: own one side of the expression.

Two things do differ. The first is that a C# operator has to live inside a type declaration, so you cannot add one to a type after the fact, at least not before the C# 14 extension operators mentioned above. The second is the one that matters more. Add is an ordinary trait, so a generic function can bound on it and get + for any type that implements it, including through your own impls. C# only got the equivalent with generic math in .NET 7, built on static abstract interface members, and an extension operator does not make its receiver satisfy IAdditionOperators, so generic math cannot see it.

The sort() call in that example is worth a second look. It works because #[derive(Ord)] gave Bytes a total order, and the signature is fn sort(&mut self) where T: Ord. Drop Ord from the derive list and the program stops compiling.

The C# equivalent checks later. List<T>.Sort() has no constraint on T at all. It reaches for Comparer<T>.Default, and if T implements neither IComparable<T> nor IComparable you get an InvalidOperationException on the line that sorts, not on the line that defined the type. Same requirement, checked at a different time.

Deriving the boring ones

Most C# codebases have hand-written Equals, GetHashCode and ToString overrides, and at least one of them is subtly wrong. Rust generates them:

Code
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
struct ServerId {
    region: String,
    index: u32,
}

Six trait implementations from one line, structurally derived from the fields. The appendix in the book is the normative list, and it is worth knowing precisely what each one writes:

  • Debug gives you {:?} formatting, which is what assert_eq! prints when a test fails, and what you want in logs.
  • PartialEq compares every field; two structs are equal when all fields are. On an enum, each variant equals only itself. Eq adds no methods at all. It is a marker saying the relation is reflexive, which is why f64 implements PartialEq but not Eq: NaN != NaN.
  • PartialOrd compares fields in declaration order, first field first. On enums, variants declared earlier sort lower. Ord promises a total order. Field order is load-bearing here, and reordering fields for tidiness silently changes your sort.
  • Hash combines the hashes of every field. Because Eq and Hash are derived from the same fields, they cannot disagree, which removes an entire category of dictionary bug.
  • Clone calls clone on each field. Copy is a marker meaning the value can be duplicated by copying its bits, with no code run, and it requires Clone.
  • Default calls Default::default on each field. On an enum you have to mark one variant with #[default].

Display is deliberately not derivable. How a type should look to a user is a decision the compiler cannot make.

Now the part where the simple model breaks. I said derive writes the implementation you would have written. It does not quite. It writes the implementation with a bound on every generic parameter:

Code
use std::rc::Rc;

#[derive(Clone)]
struct Cached<T> { inner: Rc<T> }

struct Connection;   // deliberately not Clone

fn main() {
    let c = Cached { inner: Rc::new(Connection) };
    let _copy = c.clone();
}
Code
error[E0599]: the method `clone` exists for struct `Cached<Connection>`, but its trait bounds were not satisfied
  --> src/main.rs:10:19
   |
4  | struct Cached<T> { inner: Rc<T> }
   | ---------------- method `clone` not found for this struct because it doesn't satisfy `Cached<Connection>: Clone`
...
6  | struct Connection;   // deliberately not Clone
   | ----------------- doesn't satisfy `Connection: Clone`
...
10 |     let _copy = c.clone();
   |                   ^^^^^ method cannot be called on `Cached<Connection>` due to unsatisfied trait bounds
   |
note: the following trait bounds were not satisfied:
      `Connection: Clone`
help: consider annotating `Connection` with `#[derive(Clone)]`

Cached<T> holds an Rc<T>, and cloning an Rc bumps a refcount. It never touches the T. But #[derive(Clone)] emitted impl<T: Clone> Clone for Cached<T> because it is a syntactic macro that sees a type parameter and adds the obvious bound. It cannot reason about what the fields actually need.

Take the compiler's suggestion here and you have made Connection cloneable to satisfy a bound nothing uses. The real fix is to drop the derive and write the impl you meant:

Code
impl<T> Clone for Cached<T> {
    fn clone(&self) -> Self {
        Cached { inner: Rc::clone(&self.inner) }
    }
}

C# is not without an answer here. A record generates value equality, GetHashCode, ToString, a copy constructor for with expressions, and, when it is declared positionally, Deconstruct. It does all of that well. The difference is granularity: record is a package deal attached to a kind of type, while derive is per-trait and opt-in, so you can have structural equality without ordering, or ordering without hashing, and the choices are visible on the line above the struct.

The traits worth learning first

You do not need the whole standard library. These carry most of the weight:

TraitWhat it gives youNearest C# thing
Debug{:?} formatting for logs and testsToString for debugging
Display{} formatting for users, and .to_string() freeToString
Cloneexplicit duplication, as deep as the type choosesICloneable, done properly
Copyimplicit bitwise copy, no code runvalue-type assignment
PartialEq / Eq==, and map key eligibilityIEquatable<T>
PartialOrd / Ord<, sort, BTreeMap keysIComparable<T>
HashHashMap and HashSet keysGetHashCode
Defaulta type-defined default value, and ..Default::default()parameterless constructor
From / Intoinfallible conversionimplicit conversion operators
TryFrom / TryIntofallible conversionTryParse, with a real return type
Iteratorlazy sequences, plus every adapter for freeIEnumerable<T> plus LINQ
IntoIteratorwhat for loops actually callGetEnumerator
Dropautomatic cleanup at drop points during ordinary executionIDisposable
Derefsmart pointer transparencyno real equivalent
AsRef / Borrowcheap reference conversion in APIsoverloads taking string and ReadOnlySpan<char>
Add, Index, and friendsoperatorsoperator +, this[int]
Send / Syncconstraints on transferring and sharing types between threadsthread-safety conventions and synchronization APIs

From deserves a note because it pulls its weight in error handling later. Implement From<A> for B and you get Into<B> for A free.

Blanket implementations

That last sentence is doing something specific.

This is how ToString normally works. The standard library recommends implementing Display, which gives you ToString through a blanket impl. If you implement Display and also try to implement ToString directly for the same type, the impls overlap and the compiler reports the conflict:

Code
use std::fmt;

struct Bytes(u64);

impl fmt::Display for Bytes {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{} B", self.0) }
}

impl ToString for Bytes {
    fn to_string(&self) -> String { format!("{} bytes", self.0) }
}
Code
error[E0119]: conflicting implementations of trait `ToString` for type `Bytes`
  --> src/main.rs:9:1
   |
9  | impl ToString for Bytes {
   | ^^^^^^^^^^^^^^^^^^^^^^^
   |
   = note: conflicting implementation in crate `alloc`:
           - impl<T> ToString for T
             where T: std::fmt::Display, T: ?Sized;

You can write your own. Extension traits are the common use: define a trait, blanket-implement it for everything satisfying some bound, and every one of those types gains the methods.

The cost is that a blanket impl is close to a one-way door. Ship impl<T: HealthCheck> Reportable for T in a library, and you have permanently forbidden anyone, including yourself, from writing a specific impl Reportable for MyThing. Specialization, which would let a more specific impl win, is a long-running unstable feature and you cannot rely on it. Blanket impls are a fine tool and a poor default.

Serialization, where the orphan rule actually bites

The place this stops being theory is serialization. serde::Serialize is a foreign trait. A timestamp type from some other crate is a foreign type. Coherence says you cannot connect them, and the moment your service has forty types crossing an API boundary, several of them will be exactly that combination.

serde's answer is worth studying because it is what a mature ecosystem does when it hits this wall. There is #[serde(with = "module")] to point a field at conversion functions, remote derive to generate serialization helpers from a local mirror definition, used through field attributes, and a whole crate, serde_with, that exists mostly to paper over the gap. None of that is elegant. All of it is the tax coherence charges, and it is charged at exactly the moment your dependency graph gets wide.

The other thing that changes at scale is that a trait becomes a public contract in a way an interface is not. In C#, adding a member to a widely implemented interface breaks implementors, which everyone knows. In Rust the same is true, plus the ambiguity hazard from defaulted methods, plus the fact that adding a blanket impl can break a consumer who wrote a specific one, plus the fact that changing an associated type to a generic parameter or back is a major version bump. The SemVer reference is long for a reason. If you are designing a trait that other teams will implement, treat the associated-type-versus-generic-parameter decision as an architectural one, because it is the hardest to reverse.

The mistakes to expect

Forgetting the use. You will lose time to no method named ... on a method you can see in the source. Read the help line. The compiler tells you which import is missing.

Trying to build a class hierarchy out of supertraits. trait B: A looks like class B : A, so people stack four of them and then look for the shared state. There is none. When you catch yourself writing a supertrait chain to share fields, stop and put a struct in a field instead.

Implementing ToString when Display is the intended interface. The standard library recommends Display; implementing both for the same type overlaps with the blanket impl and produces E0119. Also PartialOrd by hand when Ord is what callers need, and Ord by hand in a way that disagrees with the derived PartialOrd, which is a silent bug rather than a compile error.

Deriving Copy reflexively. Copy means assignment duplicates the value silently instead of moving it. On a small struct of numbers that is right. On anything you expect to be tracked by the ownership rules, it quietly removes the compiler's ability to tell you about a stale copy. Derive Clone first, add Copy when you have a reason.

Reaching for Box<dyn Trait> because an interface always meant run-time polymorphism in C#. Most of the time a generic parameter is what you want, and the next section is about why.

Where C# comes out ahead

Two places, honestly.

Discoverability is the first. In C#, class Database : IHealthCheck, IDisposable tells you what the type does in one line, and Go-to-Definition lands on the whole story. In Rust the impls are scattered across a file, a crate, or somebody else's crate, and answering "what does this type implement" means asking rustdoc or rust-analyzer. Tooling handles it well. Reading the source does not.

Run-time discovery is the second, and it is the bigger one. An architecture that finds its implementations by scanning at run time, which describes a lot of enterprise .NET, has no direct translation. Rust's answer is a registry you fill in by hand or a macro that builds one at compile time. Both work. Neither is as convenient as a container that just finds your handlers, and if your design leans on that, price the rewrite in before you port anything.

Checking yourself

Why can you write impl HealthCheck for i32 but not impl Display for Vec<String>? The first has a local trait, so that impl satisfies the orphan rule; it must still not overlap another applicable impl. The second has a foreign trait and a foreign type, so a cousin crate could write the identical impl and linking both would give two answers to one question.

A colleague says a supertrait is Rust's version of a base class. What is the one-sentence correction? trait B: A desugars to a where Self: A bound, so it constrains who may implement B and lets B's default bodies call A's methods, but nothing is inherited: no fields, no constructor, no overridable slot.

You are designing trait Repository. Should the entity type be an associated type or a generic parameter? Associated, if each repository handles exactly one entity, which is the usual case, and it saves every caller from annotating. Generic, only if one type genuinely needs to be a repository for several entities at once, the way From<T> is implemented many times over.

You implemented Display for your type and .to_string() works, but you never wrote it. Where did it come from, and what does that prevent you from doing? From the blanket impl<T: Display + ?Sized> ToString for T in the standard library. Because coherence permits one impl, it prevents you from writing your own ToString for that type, which is why the compiler answers with E0119 if you try.

Get the next deep dive by email

New deep dives on how production systems really behave, from Kubernetes networking to PostgreSQL internals. About one email a month.

You will get one email to confirm. Unsubscribe from any email with one click. Your address is used for this newsletter and nothing else.

Written by Zeeshan Adil

I run systems like this for a living. If your team is fighting the same problem, or wants this as a talk, write to me.