skip to content

Coherence and Orphan Rule

Rust allows at most one impl of a trait for a type, and the orphan rule says which crate may write it. Interviewers ask how to implement a foreign trait for a foreign type.

on this pageshow

questions

4

In a Rust application crate, why can't you write `impl serde::Serialize for std::time::SystemTime` to emit Unix milliseconds, and what do you write instead?

level: middleimportance: must knowfreq 55%

answer

  1. whose trait, whose type
  2. serde already ships one impl
  3. one impl per trait and type
  4. a local tuple struct around it

basics

~20 s

Serialize belongs to serde and SystemTime to std, so the impl breaks Rust's orphan rule (E0117); serde also already implements it, and coherence allows one impl per pair. Wrap the time in a local newtype and implement Serialize for that.

solid answer

~40 s

Two rules block it. The **orphan rule** forbids implementing a foreign trait for a foreign type, and both `Serialize` (serde) and `SystemTime` (std) are foreign to the application, so rustc reports E0117. Even if it allowed the impl, **coherence** permits only one impl of a trait for a type in the whole program, and serde already ships `impl Serialize for SystemTime`, which writes a struct with `secs_since_epoch` and `nanos_since_epoch`. The fix is a newtype, `struct UnixMillis(SystemTime);`, with your own `impl Serialize for UnixMillis` that writes the millisecond count. It costs nothing at run time; what you lose is the inner type's methods and trait impls, so you derive or forward the ones you need. For a single struct field, serde's `with` attribute is the lighter alternative.

code

rust · 22 lines
rust
use serde::{Serialize, Serializer};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

// A local wrapper: the impl below has a local type, so the orphan rule allows it.
struct UnixMillis(SystemTime);

impl Serialize for UnixMillis {
    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        match self.0.duration_since(UNIX_EPOCH) {
            Ok(d) => s.serialize_u64(d.as_millis() as u64),
            Err(_) => Err(serde::ser::Error::custom("time before 1970")),
        }
    }
}

fn main() {
    let t = UNIX_EPOCH + Duration::from_millis(1_700_000_000_123);
    // serde's built-in impl for SystemTime: a two-field struct
    println!("{}", serde_json::to_string(&t).unwrap());
    // the newtype's impl: one integer
    println!("{}", serde_json::to_string(&UnixMillis(t)).unwrap());
}

go deeper

for a junior

Recall that Serialize and SystemTime both come from other crates, so the orphan rule blocks the impl, and that a local wrapper struct is the standard way round it.

for a middle

Explain both rules separately: E0117 from the orphan rule, and coherence meaning serde's existing impl cannot be replaced. Then list what the newtype costs and what it does not.

for a senior

Show judgment about the fix: a field attribute for one struct, a newtype when the format must travel, and derives plus a From impl so the wrapper stays pleasant to use.

for a principal

A team-wide answer is to settle one wire type for timestamps in a shared crate, so every service serialises time the same way instead of each one writing its own wrapper.

## The situation An application talks to an API that wants timestamps as Unix milliseconds, a single integer. The struct holds a `std::time::SystemTime`, and the obvious move is to write `impl Serialize for SystemTime` that emits `as_millis()`. rustc rejects it, and two separate rules stand in the way. ## Rule one: the orphan rule (E0117) The **orphan rule** allows a trait implementation only if the trait or at least one type in the impl is defined in the current crate. Here: - `Serialize` is defined in serde, a dependency, so it is a **foreign trait**; - `SystemTime` is defined in std, also another crate, so it is a **foreign type**. rustc 1.99.1 answers with `error[E0117]: only traits defined in the current crate can be implemented for types defined outside of the crate`, labels the type with "`SystemTime` is not defined in the current crate", and ends with the note "define and implement a trait or new type instead". ## Rule two: coherence, one impl per pair The orphan rule is a means; **coherence** is the goal. For any trait and type there is at most one impl in the program, so `serde_json::to_string(&t)` always runs one known piece of code. serde already provides that impl: with its default `std` feature, it implements `Serialize` for `SystemTime` as a two-field struct, `secs_since_epoch` and `nanos_since_epoch`, and returns an error for a time before the Unix epoch. So the request is really to *replace* an existing impl, and no crate, serde included, can have two impls of `Serialize` for `SystemTime`. A crate that owned both the trait and the type would hit the same wall from the other side: a second impl of `Serialize` for `SystemTime` is E0119, "conflicting implementations", whichever crate writes it. That is why the fix is never "override": it is a different type, whose impl serde's existing one cannot touch. ## The newtype workaround A **newtype** is a tuple struct with one field, defined in your crate: 1. Declare `struct UnixMillis(SystemTime);`. The wrapper is a local type. 2. Write `impl Serialize for UnixMillis`. A foreign trait for a local type passes the orphan rule. 3. Since `UnixMillis` is a distinct type, serde's `SystemTime` impl does not apply to it, so there is no overlap. 4. Use `UnixMillis` in the fields that must serialise as milliseconds, and convert at the edges with `UnixMillis(t)` and `.0`. The example's `main` prints both encodings of the same instant: `{"secs_since_epoch":1700000000,"nanos_since_epoch":123000000}` from serde's impl and `1700000000123` from the newtype. ## What the wrapper costs | concern | effect of `struct UnixMillis(SystemTime)` | |---|---| | run time | none; the Rust Book notes the wrapper is elided at compile time | | memory layout | same size in practice; `#[repr(transparent)]` guarantees the inner field's layout and ABI | | inherent methods | gone: `duration_since` and `elapsed` need `.0` or forwarding methods | | trait impls | not inherited: derive `Clone`, `Copy`, `PartialEq`, `Ord`, `Hash` or `Debug` again | | call sites | conversions where plain `SystemTime` values enter or leave | The usual response to the lost methods: - derive the traits the inner type already implements, `#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]`, which works because `SystemTime` implements all of them; - add `From<SystemTime> for UnixMillis` so callers can write `.into()`; - forward only the handful of methods the wrapper's users really call. Implementing `Deref` to expose every method of the inner type is the tempting shortcut; whether a newtype should do that is a separate debate about `Deref` and is not needed to get past the orphan rule. ## Other ways out - **A field attribute.** serde's derive accepts `#[serde(with = "module")]` or `serialize_with` on one field, pointing at a function you write. No new type is involved; the attribute only changes how that field is serialised, so it suits a single struct. - **Your own trait.** If the code that needs the conversion is yours, a local trait implemented for `SystemTime` also passes the orphan rule, but serde will not call it. - **Upstream support.** Date and time libraries commonly ship `Serialize` impls for their own types behind an optional serde feature; only the crate that owns the type or the trait can do that. The interview point is to name both rules: the orphan rule explains the E0117, and coherence explains why even serde could not offer a second encoding as another impl for the same type.

  • Does wrapping `SystemTime` in `UnixMillis` add any run-time cost?
    No. A one-field tuple struct is compiled away; the Rust Book states there is no run-time performance penalty. It has the same size in practice, and `#[repr(transparent)]` makes the layout and ABI match the inner field when that must be guaranteed, for example across FFI. The cost is in code: lost methods, re-derived traits and conversions.
  • Why does `UnixMillis` not inherit `Debug`, `Clone` or `PartialEq` from `SystemTime`?
    Trait impls belong to a type, and `UnixMillis` is a new type with no impls of its own. You derive them again; the derives work because `SystemTime` implements each of those traits, so the generated code can delegate to the field.
  • When is serde's `with` field attribute a better fit than a newtype?
    When only one or two fields of a derived struct need the custom format. The attribute points serde at your own serialise function for that field, so the field keeps its plain `SystemTime` type. A newtype is better when the format travels: many structs, collections of timestamps, or other code that should not forget the conversion.

  • Putting the impl in a private module of your crate makes it legal.
  • A more specific impl in your crate overrides serde's impl for SystemTime.
  • A newtype adds a pointer indirection or heap allocation per value.
  • The newtype automatically gets all of SystemTime's methods and trait impls.
  • Only the crate that defines SystemTime may implement traits for it.
open as a page

In Rust, may your crate implement its own trait for `String`, a std trait for its own struct, and `std::fmt::Display` for `Vec<u8>`?

level: juniorimportance: should knowfreq 45%

basics

~20 s

Yes, yes, no. Rust's orphan rule lets a crate implement a trait for a type only when the trait or the type is defined in that crate; Display and Vec<u8> both come from std, so rustc rejects that impl with E0117.

open as a page

A Rust crate defines `trait Encode` with a blanket `impl<T: Display> Encode for T`; why does adding `impl Encode for SystemTime` fail with E0119 although `SystemTime` has no `Display` impl?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Rust's overlap check must survive std adding impl Display for SystemTime in a later release, when both impls would apply. rustc assumes an impl is absent only where no other crate could add it, as for a local type.

open as a page

In Rust, why does rustc accept `impl From<Celsius> for f64` and `impl IntoIterator for &Readings`, yet reject `impl fmt::Display for Vec<Celsius>` with E0117?

level: seniorimportance: should knowfreq 25%

basics

~20 s

The orphan rule needs one local type anywhere in the impl header, with no uncovered type parameter before it. Celsius as From's argument qualifies; &Readings is local because & is fundamental; Vec<Celsius> is a foreign Vec.

open as a page