The Adapter Pattern in Rust: Getting Around the Orphan Rule Using Newtypes and Extension Traits
This article looks at the Adapter pattern in Rust as a practical way of dealing with the Orphan Rule – the language restriction that forbids implementing external traits for external types. It begins by explaining clearly why the Orphan Rule exists and which compilation problems it leads to, then shows step by step how to build a newtype-based adapter, how to turn it into one that holds a reference with explicit lifetimes, and how to wrap everything in an extension trait to get a clean, ergonomic API. A real-world example connects the axum and eyre crates, demonstrating how several specialized adapters can map errors onto particular HTTP status codes. The article also discusses design questions such as Deref and AsRef implementations, public vs. private inner fields, and situations in which third-party options like serde's remote syntax may suit better than a hand-written adapter.
Let’s first recall the Newtype pattern in the Rust programming language. In that pattern, a single-field tuple struct serves either to change the semantics of the inner type or to conceal the implementation type from the end user - and frequently we are after both.
In this post, we’ll again examine the single-field tuple struct, but this time we’ll use it to implement the adapter pattern. Let’s begin by describing the problem it is meant to solve.
Orphan Rule
In my experience, Rust’s typesystem is among the hardest things to truly understand - simply because it differs so much from the object-oriented languages we are accustomed to.
One of its unusual aspects is how Traits relate to user-defined types. Traits are usually presented as an implementation of interfaces. Since both serve a similar role - abstraction at the level of behavior - I personally avoid describing traits as interfaces too readily, because there is an important difference between them. We normally think of interfaces as being tied to a type at the point where the type is declared. So when we define the Orc type, we list right away every interface it implements - Creature, Foe, Mesh. Traits don’t work like that. In Rust, traits and types are fully orthogonal and defined independently of each other. For public types, you can never claim to know every trait implemented for the type - dependent crates can always add to that set.
This, however, creates a problem. Suppose we have two crates, crate1 and crate2, each consisting of a single lib.rs file:
// crate1/lib.rs
trait Applicator {
fn apply(&self, a: u32) -> u32;
}
// crate2/lib.rs
struct Multiplicator {
pub scale: u32,
}
The author of crate2 knows nothing about crate1's existence, and vice versa. There is, however, a crate3 whose author wants to use both crates and needs Applicator to be implemented for the Multiplicator type:
use crate1::Applicator;
use crate2::Multiplicator;
impl Applicator for Multiplicator {
fn apply(&self, a: u32) -> u32 {
self.scale * a
}
}
That looks sensible, and it’s something we would really like to be able to do. The bad news: this code won’t compile. Let’s consider why that’s a problem.
To see it, let’s add a crate4, which has a somewhat different idea of how Applicator should be implemented for Multiplicator:
use crate1::Applicator;
use crate2::Multiplicator;
impl Applicator for Multiplicator {
fn apply(&self, a: u32) -> u32 {
a.pow(self.scale)
}
}
So far so good, isn’t it? crate3 relies on its own trait implementation, crate4 relies on its own, and all is well. Things get complicated, though, once we add crate5, which depends on every crate mentioned so far:
use crate1::Applicator;
fn main() {
let m = crate2::Multiplicator { scale: 3 };
println!("{}", m.apply(3));
}
Here’s the question: what does crate5 print? 9 or 27? There’s no way to tell which implementation is the right one!
One possible answer: simply refuse to compile when this situation arises! crate5 could just trigger a compilation error because of the conflicting implementations of Applicator for Multiplicator. That would be short-sighted, however. Perhaps at the time crate5 was written, crate4 didn’t need an Applicator implementation yet, and the plan was to rely on the crate3 implementation that had always been present. In that situation, the code would compile fine until crate4 introduced its new trait implementation. That’s not what we want - it would make managing dependencies extremely hard.
Rather than that, the creators of Rust settled on what is known as the Orphan Rule. Its complete formulation is rather involved, since it covers some cases with generics, but the simplified version I like to use goes like this:
To implement a trait for a type, the crate containing the impl block must own the trait or the type.
The tricky part concerns generic types - it turns out that in those cases, both the generic type and the trait may come from external crates, provided that the crate with the impl block owns a type used to specialize the generic. The complete rule is described in the Rust reference.
The problem
Let’s return to crate3 from the example above. Here is its code again:
use crate1::Applicator;
use crate2::Multiplicator;
impl Applicator for Multiplicator {
fn apply(&self, a: u32) -> u32 {
self.scale * a
}
}
This is what we get when we try to compile it:
error[E0117]: only traits defined in the current crate can be implemented for types defined outside of the crate
--> src/lib.rs:4:1
|
4 | impl Applicator for Multiplicator {
| ^^^^^^^^^^^^^^^^^^^^-------------
| |
| `Multiplicator` is not defined in the current crate
|
= note: impl doesn't have any local type before any uncovered type parameters
= note: for more information see https://doc.rust-lang.org/reference/items/implementations.html#orphan-rules
= note: define and implement a trait or new type instead
Yet this is exactly the use case we need very often! I ran into this problem recently while using the axum crate for a web server. axum has its axum::response::IntoResponse trait, meant to be implemented for types that can be turned into an HTTP response. A handy property of this trait is that when axum::response::IntoResponse is implemented for both T and E, it is implemented for Result<T, E> as well - so all we want is to implement the trait for the error types we define!
Since I’m building a binary application rather than a library, I prefer the eyre (or anyhow) crate for error handling. Here’s the catch - axum is unaware of either of those crates. And neither crate implements axum traits. So if I want my eyre errors to just produce 500 HTTP responses, I’m stuck - I can’t simply implement a trait! The straightforward fix is the Adapter pattern.
Adapter pattern
The adapter pattern is just a newtype, exactly as the compiler suggested, that implements the traits our external type lacks. Let’s use it to fix crate3:
struct ApplicatorAdapter(crate2::Multiplicator);
impl crate1::Applicator for ApplicatorAdapter {
fn apply(&self, a: u32) -> u32 {
self.0.scale * a
}
}
impl ApplicatorAdapter {
fn new(src: crate2::Multiplicator) -> Self {
Self(src)
}
}
To use the Applicator trait now, we just build the adapter first:
fn mul(a: u32, b: u32) -> u32 {
let m = Multiplicator { scale: a };
let adapter = ApplicatorAdapter::new(m);
adapter.apply(b)
}
Reference as underlying type
The above solution already works. It has a major drawback, though: building the adapter requires full ownership of the Multiplicator. As a result, the adapter is useless if we want to keep the original object afterwards, or if all we have is a reference, which, given the Applicator definition, ought to be enough.
To address this, we frequently make the adapter hold a reference internally rather than an owned value. Using this approach, crate3 might look like this:
struct ApplicatorAdapter<'a>(&'a crate2::Multiplicator);
impl crate1::Applicator for ApplicatorAdapter<'_> {
fn apply(&self, a: u32) -> u32 {
self.0.scale * a
}
}
impl<'a> ApplicatorAdapter<'a> {
fn new(src: &'a crate2::Multiplicator) -> Self {
Self(src)
}
}
Using a reference as the inner type forced us to add a lifetime generic, because every reference has to be tied to some lifetime. Here, it ensures the ApplicatorAdapter struct can never outlive the Multiplicator it was built from. That’s logical; the wrapper holds a reference, so if it outlived the inner Multiplicator, we’d end up with a highly dangerous dangling reference.
Keep in mind that if the method of the Applicator trait required &mut self, we’d just use a mutable reference internally. That would be somewhat troublesome, however - it would mean always needing a mutable reference to the object, even to call &self methods of Applicator. In those situations, the usual approach is to use an owning adapter and offer an API for turning it back into the inner object, such as a fn into_inner(self) -> Multiplicator method on the adapter type.
Extension trait for creation
The adapter pattern got us around the orphan rule, but it brought a new problem: the API has become irritating. We have to build a whole new type for one call, the name is long, and there are lots of characters to type and read. We could shorten the adapter type name, but even then I don’t like the resulting API.
The usual remedy is another pattern that’s very common in Rust - the extension trait. The idea is to define a new crate-private trait and implement it for the adapted type, thereby giving it new functionality. The orphan rule won’t get in our way - the trait definition is ours. Here is how this might look:
trait AdapterBuilder {
fn applicator(&self) -> impl crate1::Applicator;
}
impl AdapterBuilder for Multiplicator {
fn applicator(&self) -> impl crate1::Applicator {
ApplicatorAdapter(self)
}
}
fn mul(a: u32, b: u32) -> u32 {
let m = Multiplicator { scale: a };
m.applicator().apply(b)
}
The Applicator can also be used when we only have access to a Multiplicator reference:
fn mul1(m: Multiplicator, b: u32) -> u32 {
m.applicator().apply(b)
}
Deref and AsRef on the adapter type
Next, I’d like to touch on a somewhat controversial subject - should adapter types implement Deref, and perhaps DerefMut?
The obvious starting point is the Deref documentation:
Warning: Deref coercion is a powerful feature of the language with wide-ranging consequences for any type implementing Deref. The compiler inserts calls to Deref::deref silently. That is why implementing Deref calls for caution and should be done only when deref coercion is wanted. Guidance on when it is usually desirable or undesirable follows below.
Types implementing Deref or DerefMut are commonly referred to as “smart pointers”, and deref coercion was designed specifically to support the pointer-like behavior that this name implies. A “smart pointer” type typically exists to alter the ownership semantics of the value it contains (e.g. Rc or Cow) or its storage semantics (e.g. Box).
The key question is whether coercion is desirable for an adapter. The documentation’s standard example is smart pointers. It’s hard to consider an adapter a smart pointer - storage semantics have nothing to do with it. Still, does the documentation strictly forbid using Deref on things that aren’t smart pointers?
Personally, I implement the Deref and DerefMut traits for my adapter types quite often, particularly for owning adapters. It always depends on how I intend to use the adapter. If it’s a short-lived ad hoc type that I create in some scope only to call a few trait methods, I may leave out Deref. On the other hand, I frequently build a single adapter for a type that is central to my solution, implementing a whole set of missing traits, and then use that type nearly everywhere in place of the adapted one - in that case I may define both Deref and DerefMut to retain the original type’s implementation via coercion - which is usually exactly what I want.
If implementing Deref feels like too strong a break with idioms for you, an alternative is to implement the AsRef and possibly AsMut traits to keep on-demand access to the original object. The drawback of those traits is that they’re generic, and sometimes you have to explicitly specify which type you want to coerce to.
One more option is to offer a function on the adapter type that gives direct access to the inner type:
impl<'a> ApplicatorAdapter<'a> {
fn as_inner(&self) -> &'a Multiplicator {
self.0
}
}
The conventional name for a method returning a mutable reference (for mutable-reference or owning adapters) is as_inner_mut.
Solving Axum problem with adapter
Let’s go back to the practical problem I ran into – connecting axum with the eyre crate. Axum offers the axum::response::IntoResponse trait, which we’d very much like implemented for the error types used in our solution - for me, that was eyre::Report. The orphan rule, however, stops us from implementing axum traits for an eyre type. The adapter pattern lets us work around this:
struct ErrorAdapter(eyre::Report);
impl axum::response::IntoResponse for ErrorAdapter {
fn into_response(self) -> axum::response::Response {
(
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
"Internal server error",
).into_response()
}
}
To make it convenient at the call site, we can implement From, which lets the ? operator work directly in handlers:
impl From<eyre::Report> for ErrorAdapter {
fn from(e: eyre::Report) -> Self {
ErrorAdapter(e)
}
}
async fn my_handler() -> Result<impl IntoResponse, ErrorAdapter> {
let data = fetch_data().await?; // eyre::Report converts into ErrorAdapter via From
Ok(axum::Json(data))
}
Multiple adapters on trait-type pair
Our axum-eyre error bridge has one issue. Every error we return becomes a 500. That’s likely the most sensible default, but sometimes we want a more specific kind of error. We can achieve this by defining several adapters for our eyre error type:
struct ErrorAdapter404(eyre::Report);
impl axum::response::IntoResponse for ErrorAdapter404 {
fn into_response(self) -> axum::response::Response {
(
axum::http::StatusCode::NOT_FOUND,
"Resource not found",
).into_response()
}
}
struct ErrorAdapter403(eyre::Report);
impl axum::response::IntoResponse for ErrorAdapter403 {
fn into_response(self) -> axum::response::Response {
(
axum::http::StatusCode::FORBIDDEN,
"Forbidden resource",
).into_response()
}
}
trait ErrExt {
fn err500(self) -> ErrorAdapter;
fn err404(self) -> ErrorAdapter404;
fn err403(self) -> ErrorAdapter403;
}
impl ErrExt for eyre::Report {
fn err500(self) -> ErrorAdapter { self.into() }
fn err404(self) -> ErrorAdapter404 { ErrorAdapter404(self) }
fn err403(self) -> ErrorAdapter403 { ErrorAdapter403(self) }
}
Notice that we can now either use a plain ? to rely on the Into error conversion, or call my_result.map_err(ErrExt::err404) to wrap the inner error in the 404 adapter. With extension traits, though, we can take it a step further - extending the result type to make the API even nicer!
trait ResultExt {
type Ok;
fn or500(self) -> Result<Self::Ok, ErrorAdapter>;
fn or404(self) -> Result<Self::Ok, ErrorAdapter404>;
fn or403(self) -> Result<Self::Ok, ErrorAdapter403>;
}
We can still use ? whenever we want to report a 500 error, but we can also just call my_result.or404()? to turn the error into the adapter dedicated to returning 404 errors.
An even more robust solution might be possible - perhaps the error code could be injected into the specialized adapter so that we don’t need a separate type per error code. Another option would be to use error code traits as marker types for ErrorAdapter, supplying just the error code as an associated constant of the trait. These, however, are further developments of the same adapter idea, so to stay focused I’ll leave them as ideas for improvement without exploring them further.
Adapter alternatives - trait crate utilities
Note that the adapter pattern isn’t always necessary to work around the Orphan Rule’s restrictions. Other ways out sometimes exist. The serde crate is a good example. When we use a type from an external crate that doesn’t implement serde’s Serialize and Deserialize traits, we might be tempted to write an adapter type that implements them. That isn’t needed, though. The serde authors recognized how common this situation is and added a dedicated remote syntax that solves the problem for us.
In the first example we discussed earlier, the Multiplicator type didn’t implement the serde types. Serde offers a dedicated mechanism for delegating the serialization of such types, sparing us from implementing Serialize or Deserialize by hand, which is often complicated:
#[derive(Serialize, Deserialize)]
#[serde(remote = "crate2::Multiplicator")]
struct MultiplicatorDef {
pub scale: u32,
}
#[derive(Serialize, Deserialize)]
struct Wrapper {
#[serde(with = "MultiplicatorDef")]
multiplicator: Multiplicator,
}
The remote syntax is highly specific to serde and is useful for more than implementing serde traits for types from other crates, but that goes beyond the scope of this article. What I want to point out is that before reaching for the adapter pattern to get past the orphan rule, it’s a good habit to check whether the crate that defines the trait offers a special syntax that helps in a more consistent way.
Public or private?
There’s one more aspect I haven’t addressed yet, which has been a topic of debate around newtype patterns. Should the type’s single field be public or private?
Unlike in the pure newtype pattern, hiding the inner implementation type isn’t the problem we’re trying to solve here. Given that, there’s frequently no real reason to make the field private. Another question arises, though: is .0 a good API to pass around? I personally dislike it, and when using single-field tuple structs for my adapters, I usually keep the field private and expose it through the Deref trait or a dedicated method.
On the other hand, if we’re adding an extra method anyway, perhaps it’s better to turn the single field into a named field rather than using a tuple struct. ApplicatorAdapter could be reworked into:
struct ApplicatorAdapter {
pub inner: Multiplicator,
}
Provided there are no further reasons to hide the underlying type, I consider this approach idiomatic. It’s often a matter of taste, as well as of the specific circumstances in which the type is used. So my view is this: for the adapter itself, visibility isn’t something to worry about.
Summary
In this article, we examined another use of the newtype-like pattern: the adapter. It is especially handy in Rust - more than in other languages - because traits and types are orthogonal, and because of the Orphan Rule that results from this.
The main lesson is that the adapter is a universal solution. Serde has remote, some crates provide feature flags for cross-crate trait implementations, but when nothing like that is available - which is frequently the case - the adapter is an excellent tool. We saw this with axum and eyre: two popular crates that know nothing about each other and offer no built-in bridge.
We also looked at how to make adapters ergonomic. A bare adapter type can feel awkward by itself, but with extension traits, From implementations, and thoughtful API design, they become almost invisible at the call site. The pattern scales smoothly from a single trait-type pair to several specialized adapters, as the HTTP error code variants showed.
In the next article, we’ll examine extension traits more closely - a pattern we’ve already used here to make adapters more ergonomic, but one that, as a powerful Rust idiom, merits its own spotlight.