medium.com 6 min read Original Source

I Stopped Treating Rust Traits Like Interfaces. Here’s Everything I Was Wrong About

The first surprise: walking into a house you don’t own and changing the furniture

In Java, a type declares its interfaces the moment it’s born. implements Comparable sits in the class definition itself, a decision made once, by whoever wrote that class, and never revisited by anyone downstream. You cannot arrive later and hand a class an interface it never asked for.

Rust lets you walk in afterward and simply add the behavior:

String;
}

impl Summary for Vec {
fn summarize(&self) -> String {
format!("a vector with {} elements", self.len())
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

trait Summary {
    fn summarize(&self) -> String;
}

impl Summary for Vec<i32> {
    fn summarize(&self) -> String {
        format!("a vector with {} elements", self.len())
    }
}
trait Summary {
    fn summarize(&self) -> String;
}

impl Summary for Vec<i32> {
    fn summarize(&self) -> String {
        format!("a vector with {} elements", self.len())
    }
}

Vec<i32> was written by people who have never heard of Summary, because Summary didn’t exist yet when they wrote it. None of that matters. The two meet here, in my code, and the compiler is satisfied. I’ve handed an existing, foreign type a new ability without touching its source and without wrapping it in something new of my own. There is no real Java shape for this. An interface there is a promise made at birth. A trait here can be a promise made much later, by someone who was never in the room when the type was born.

The reason this doesn’t collapse into chaos is a rule with a slightly forlorn name: the orphan rule. You may implement a trait for a type only if you own the trait, or you own the type, or both. I can give Vec my own Summary, because Summary is mine to give. I cannot reach into the standard library and decide how Vec implements the standard library’s own Display, because neither belongs to me, and if that door were open, two strangers’ crates could each quietly decide the same foreign type should wear the same foreign trait differently, and the compiler would have no way to know whose decision was supposed to win. The rule is what keeps the house from filling up with furniture nobody agreed on.

The second surprise: the free method was never the interesting gift

Yes, a trait can carry a default implementation, and Java’s interfaces have carried the same thing since version 8. That parity is real, and it is the least interesting thing true about traits, which is exactly why stopping there is where the assumption first goes quiet and wrong.

String;
fn greet(&self) -> String {
format!("Hello, {}!", self.name())
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

trait Greet {
    fn name(&self) -> String;
    fn greet(&self) -> String {
        format!("Hello, {}!", self.name())
    }
}
trait Greet {
    fn name(&self) -> String;
    fn greet(&self) -> String {
        format!("Hello, {}!", self.name())
    }
}

Any type providing name() receives greet() for free, still free to override it if it wants something else. Unremarkable so far.

What Java cannot do is let that default method lean on Self without knowing what Self will turn out to be, and still walk away with a version specialized down to the metal for every concrete type, at compile time, costing nothing at the moment it actually runs. Java’s default methods travel through the same dynamic dispatch every interface call in Java has always used. Rust’s don’t have to make that trip at all.

The third surprise: two different rooms hiding behind one doorway

This is the one that reshapes how you write a function signature, and it’s where “just an interface” finally falls over completely.

String {
item.summarize()
}
// Dynamic dispatch: one function, resolved through a table of
// pointers at runtime, willing to accept genuinely different
// concrete types through the same reference.
fn describe_dynamic(item: &dyn Summary) -> String {
item.summarize()
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

// Static dispatch: the compiler builds a separate, specialized
// version of this function for every concrete type it meets.
fn describe_static(item: &impl Summary) -> String {
    item.summarize()
}
// Dynamic dispatch: one function, resolved through a table of
// pointers at runtime, willing to accept genuinely different
// concrete types through the same reference.
fn describe_dynamic(item: &dyn Summary) -> String {
    item.summarize()
}
// Static dispatch: the compiler builds a separate, specialized
// version of this function for every concrete type it meets.
fn describe_static(item: &impl Summary) -> String {
    item.summarize()
}
// Dynamic dispatch: one function, resolved through a table of
// pointers at runtime, willing to accept genuinely different
// concrete types through the same reference.
fn describe_dynamic(item: &dyn Summary) -> String {
    item.summarize()
}

&impl Summary is a generic function wearing a trait bound as its only visible clothing. The compiler monomorphizes it, one bespoke copy per concrete type, the same tailoring that makes ordinary generics free at runtime. &dyn Summary is a trait object: a pointer to the data, and beside it, a pointer to a table of function pointers resolved only once the program is actually running, the identical machinery sitting under every interface call Java has ever made. The two doorways look almost the same from the hallway. They lead to entirely different rooms.

Java never makes you choose, because Java only built the second room. Every interface call there takes the dynamic path, always, by design. Rust hands you both keys and asks you to pick one, which is exactly why a trait object comes with a rule Java interfaces never needed to know about: a trait can only become a dyn Trait if it is “object safe,” which mostly rules out generic methods and methods returning Self by value, because a table of function pointers has no way to represent a return type that depends on which concrete thing is standing behind the pointer at the moment someone asks. Generics never meet that problem, since the concrete type was already settled, in daylight, before the vtable question could even be raised.

The fourth surprise: a name that lives inside the promise itself

Option;
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

trait Container {
    type Item;
    fn get(&self, index: usize) -> Option<&Self::Item>;
}
trait Container {
    type Item;
    fn get(&self, index: usize) -> Option<&Self::Item>;
}

Item here is an associated type, and each implementor of Container chooses exactly one concrete meaning for it, once, and every method on the trait can then speak of Self::Item without the trait itself ever needing a generic parameter to carry that choice around. This is precisely how Iterator works in the standard library, and it’s why you write impl Iterator<Item = u32> instead of threading a type parameter through every method signature the iterator touches.

Java’s nearest relative is a generic interface, Iterator<T>, and it resembles this just enough to mislead you. A Java class implementing Iterator<T> can be written generically itself, free to become Iterator<String> here and Iterator<Integer> there depending on who instantiates it, because the type parameter belongs to the usage, not to a single fixed decision the class made once and forever. A Rust type implementing Container names its Item a single time, permanently, for that implementation. This is exactly where a trait with a generic parameter and a trait with an associated type part ways: a trait written as Container<T> could be implemented for the same type twice, once for Container<String> and once for Container<u32>, the same way Java’s generic interfaces allow. A trait written with type Item instead cannot; a single implementation commits to exactly one meaning for Item and there is no second implementation to give it another. That restriction is the design intent, not an accident of syntax, and the trait is saying every implementor has exactly one of these, not every implementor is generic over one of these, which is a difference in what’s being promised, not merely a difference in spelling.

The fifth surprise: a promise made on behalf of types that don’t exist yet

String;
}

impl Describe for T {
fn describe(&self) -> String {
format!("value: {}", self)
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

trait Describe {
    fn describe(&self) -> String;
}

impl<T: std::fmt::Display> Describe for T {
    fn describe(&self) -> String {
        format!("value: {}", self)
    }
}
trait Describe {
    fn describe(&self) -> String;
}

impl<T: std::fmt::Display> Describe for T {
    fn describe(&self) -> String {
        format!("value: {}", self)
    }
}

This one block grants Describe to every type that already knows how to Display itself, all at once, permanently, including types nobody has written yet that will be born next year already carrying this gift without asking for it. This is a blanket implementation, and Java has nothing that answers to it, because Java has no way to say any type satisfying this other promise automatically satisfies this one too, here is the shared reasoning, once, for all of them. The nearest Java gets is a static utility method or an abstract base class, and neither one lets a stranger’s type opt in automatically merely by already keeping a different promise.

What actually survives the crossing, and what doesn’t

The part that carries over cleanly: a trait, like an interface, is a promise about behavior, and a trait bound on a generic function is answering the same question a bounded Java generic already answers, what am I allowed to assume about a type I have not met yet.

Everything past that point is where the resemblance runs out of road. Extending a house you don’t own, choosing between two different doorways instead of always being handed the same one, a name that commits an implementor once rather than travelling with every use, a gift bestowed on types that haven’t been written yet, none of it has a real Java shadow, and treating traits as interfaces wearing a different hat is exactly the assumption that kept quietly costing me, right up until I stopped making it.

If you’re prepping for interviews or just want the fast reference: Rust vs. Java — The Data Structures Cheat Sheet is free — Big-O for every structure, the full 55-problem interview index by chapter, and the three rules that separate a senior answer from a junior one.

If you’re curious how these same interface and dispatch questions play out on the Java side, that’s the whole premise of the book I’ve been writing: every classic data structure built once in Rust and once in Java, side by side, so you can see exactly where each language’s rules force a different decision. Ownership vs. Reference: Data Structures and Algorithms in Rust and Java

For the Rust foundations that series builds on: Zero to Rust: A Systems Programmer’s Field Guide — $7 · Free 20-page sample