Choosing between enum and trait: the expression problem in Rust
Background
At work I write Ouroboros, one of the many plugins for Picodata. It continuously moves data changes from one cluster to another, or to Kafka.
A lot of the code depends on where the data comes from and where it goes, and different parts of the code express this differently. When the schema changes in a Picodata source cluster (say, a column is added), rows read under the old schema must reach the destination before the change itself does. That is what the barrier is for: it holds the change until all readers catch up with it. With a Tarantool source, schema changes are not replicated, and there is no barrier. Right now the barrier is an enum:
enum SchemaBarrier {
Tarantool,
Picodata(PicodataBarrier),
}
Since the enum is stored, sooner or later you have to work with it: match on it and run some code in each variant, or define a method on the enum.
Here it is a method. For example, stopping the barrier:
impl SchemaBarrier {
fn stop(&mut self) {
match self {
Self::Tarantool => {}
Self::Picodata(b) => b.stop(),
}
}
}
One variant has a whole mechanism behind its arm, the other has nothing. There are only two sources, Tarantool and Picodata, and there will be no others, so the set of variants here is closed.
Take another example. The Tarantool replication stream delivers “packets” that tell the subscriber some operation happened on the master. Ouroboros does not need some of them. Hence the filter, which decides whether to pass a packet on to the Writer (the component that writes to the destination) or drop it. The filter is a trait with one method:
#[async_trait]
trait Filter {
async fn apply(&self, packet: Packet) -> Option<Packet>;
}
Filters are assembled into a chain, Vec<Box<dyn Filter>>, and every packet goes through it. The same filter could be expressed as an enum, and then the chain would become Vec<Filter> without Box:
enum Filter {
Space(SpaceFilter),
Bucket(BucketFilter),
Shard(ShardFilter),
}
impl Filter {
async fn apply(&self, packet: Packet) -> Option<Packet> {
match self {
Self::Space(f) => f.apply(packet).await,
Self::Bucket(f) => f.apply(packet).await,
Self::Shard(f) => f.apply(packet).await,
}
}
}
Since there are at least two ways, the question is which one to prefer and when.
The general model
Leaving Ouroboros aside, Rust has two ways to express behaviour that depends on the type. The first is an enum with a variant per type, and a method that uses match to forward the call to the variant’s method of the same name. The second is a trait with an implementation per type. On the left is the enum, on the right a trait with the same behaviour.
enum Writer {
Tarantool(Tarantool),
Kafka(Kafka),
}
impl Writer {
fn write(&self, b: &Batch) {
match self {
Self::Tarantool(w) => w.write(b),
Self::Kafka(w) => w.write(b),
}
}
}
let w = Writer::Kafka(kafka);
w.write(&batch);
trait Writer {
fn write(&self, b: &Batch);
}
impl Writer for Tarantool {
fn write(&self, b: &Batch) { /* … */ }
}
impl Writer for Kafka {
fn write(&self, b: &Batch) { /* … */ }
}
let w: Box<dyn Writer> = Box::new(kafka);
w.write(&batch);
Note that:
- the calling code looks the same in both cases
- both ways let each type hold any data of its own
There are differences too:
- with an
enumthe list of types is written in one place and the compiler knows all of it, while anyone can add a trait implementation, including another crate - the size of an
enumis known at compile time and the value sits right in the variable, while a trait object lives behind a pointer, usually on the heap viaBox - with an
enumthe right arm is picked bymatch, with a trait object by a virtual method table at run time
In general terms: there is a set of types and a set of operations on them. The code has to perform every operation for every type, that is, fill in a table with types as rows and operations as columns.
operation f |
operation g |
new operation | |
|---|---|---|---|
type A |
yes | yes | ? |
type B |
yes | yes | ? |
| new type | ? | ? | ? |
Hence the question:
How do you choose between an enum and a trait if both new types and new operations on them get added over time?
First let’s see what people say about it on forums, and then check those opinions against the classic literature.
Folk wisdom
Forums are a handy way to get your bearings in a topic and find more authoritative sources.
In 2017 someone on users.rust-lang.org asked whether enums are harmful in general. The well-known Rust evangelist Steve Klabnik answered:
Enums are for closed sets, and trait objects are for open sets. That is, if you know every variant, you go with an enum. If you don’t, then you go with a trait object.
Steve Klabnik, users.rust-lang.org, 2017
The rule is simple but raises questions: it only looks at whether the set of variants is closed and says nothing about the set of operations. In simple cases it works:
Result<T, E>andOption<T>have exactly two variants by definition, and no others will appear, so they are enums.std::io::Writeis implemented by everyone who needs to write bytes somewhere: files, sockets, in-memory buffers, third-party libraries. The set of implementations is open, so it is a trait.
But often it is not even clear whether the set is closed. We write all the filters in Ouroboros ourselves, and at any moment their list is known, so the set seems closed. Yet new filters appear as needed, and in that sense the set is open.
In the same thread, user HadrienG wrote about operations. He went through two kinds of change. In the examples below, Tarantool, Kafka and Picodata in the trait version are wrappers around a connection: struct Tarantool(Conn), struct Kafka(Producer), struct Picodata(Client).
First: what happens if you add a new operation, say stop. With an enum it is a new method with a match, and the rest of the code stays the same. With a trait the new method has to be written in every implementation, including other people’s code if the trait is public. The additions are highlighted:
enum Writer {
Tarantool(Conn),
Kafka(Producer),
}
impl Writer {
fn write(&self, b: &Batch) {
match self {
Self::Tarantool(c) => c.insert(b),
Self::Kafka(p) => p.send(b),
}
}
fn stop(&mut self) {
match self {
Self::Tarantool(c) => c.close(),
Self::Kafka(p) => p.flush(),
}
}
}
trait Writer {
fn write(&self, b: &Batch);
fn stop(&mut self);
}
impl Writer for Tarantool {
fn write(&self, b: &Batch) {
self.0.insert(b)
}
fn stop(&mut self) {
self.0.close()
}
}
impl Writer for Kafka {
fn write(&self, b: &Batch) {
self.0.send(b)
}
fn stop(&mut self) {
self.0.flush()
}
}
Second: what happens if you add a new type, say Picodata. With a trait it is a new impl, and the rest of the code stays the same. With an enum you have to go through every match:
enum Writer {
Tarantool(Conn),
Kafka(Producer),
Picodata(Client),
}
impl Writer {
fn write(&self, b: &Batch) {
match self {
Self::Tarantool(c) => c.insert(b),
Self::Kafka(p) => p.send(b),
Self::Picodata(c) => c.sql(b),
}
}
fn stop(&mut self) {
match self {
Self::Tarantool(c) => c.close(),
Self::Kafka(p) => p.flush(),
Self::Picodata(c) => c.close(),
}
}
}
trait Writer {
fn write(&self, b: &Batch);
fn stop(&mut self);
}
// impls for Tarantool and Kafka
// stay as they were
impl Writer for Picodata {
fn write(&self, b: &Batch) {
self.0.sql(b)
}
fn stop(&mut self) {
self.0.close()
}
}
His conclusion:
The trade-off between enums and trait objects for OO programming is really pretty simple: traits make it easy to add new implementations, whereas enums make it easy to add new interface methods. The choice between them depends on which of these things you expect to have highest variability in the final software.
If you go with an enum and a new variant has to be added later on, then you’ll need to modify every pattern matching in your code. If you go with a trait and a new method has to be added later on, then you’ll need to review and possibly modify every single implementation of that trait in your code AND other people’s code if the trait is public. In both cases, you will suffer.
HadrienG, users.rust-lang.org, 2017
But there is more to the choice than the cost of change.
First, an enum does not hide its variants. In the same thread, user withoutboats writes that anyone who has an enum value can destructure it and get to the specific variant. A trait object exposes only the trait’s methods.
pub enum Writer {
Tarantool(Conn),
Kafka(Producer),
}
// in another module
if let Writer::Kafka(p) = &w {
p.flush();
}
pub trait Writer {
fn write(&self, b: &Batch);
}
// in another module
w.write(&batch);
On the left, other code relies on the Kafka variant holding a Producer and will break if that changes. On the right, only what the trait declares is available.
Second, an enum and a trait group code differently. User nivenkos writes about this on Reddit in 2020, while moving a project from enums to trait objects. Generalizing the observation: traits group code by implementation, enums by operation. With a trait everything about Kafka is in one impl, but the stop operation is spread across all implementations. With an enum it is the other way round: stop is all in one function, and the Kafka code is spread across the arms of every match.
enum Writer {
Tarantool(Conn),
Kafka(Producer),
}
impl Writer {
fn write(&self, b: &Batch) {
match self {
Self::Tarantool(c) => c.insert(b),
Self::Kafka(p) => p.send(b),
}
}
fn stop(&mut self) {
match self {
Self::Tarantool(c) => c.close(),
Self::Kafka(p) => p.flush(),
}
}
}
trait Writer {
fn write(&self, b: &Batch);
fn stop(&mut self);
}
impl Writer for Tarantool {
fn write(&self, b: &Batch) {
self.0.insert(b)
}
fn stop(&mut self) {
self.0.close()
}
}
impl Writer for Kafka {
fn write(&self, b: &Batch) {
self.0.send(b)
}
fn stop(&mut self) {
self.0.flush()
}
}
Third, the least obvious answer came from user sfackler. The thread’s author was afraid that a single change would force rewriting hundreds of match statements, and sfackler replied that this is exactly why you pick an enum:
You use an enum when you want to be forced to handle the addition in every use site.
sfackler, users.rust-lang.org, 2017
A bit earlier in the same post, sfackler writes that trait objects are good when the calling code does not care which implementation it has. If the calling code makes the decision itself, you need an enum. For example, the calling code decides whether a Kafka destination can be connected to a Picodata source. When a new destination appears, the compiler will make you answer that question for it too, while with a trait it is easy to forget.
Putting it all together:
- HadrienG: look at what will grow, types or operations. An
enummakes new operations easy, a trait makes new types easy. - sfackler: you pick an
enumwhen you want the compiler to make you handle a new variant everywhere. - nivenkos: a trait groups code by implementation, an
enumby operation. - withoutboats: an
enumcan be destructured from outside, a trait shows only its methods.
All these answers are about the table of types and operations we started with: how to add both rows and columns to it. This problem has a name, the expression problem, and the literature has been discussing it much longer than Rust has existed.
The expression problem
In 2025 lobste.rs discussed the article “The expression problem and Rust”, and one of the replies goes like this:
Yeah, the expression problem is only a problem when there’s library code that you’re using but cannot modify. If all the code is in your version control system, you can “solve” the expression problem by using an
enumwith methods on it. To add more data, you add another case to theenumand update the methods. To add another method, you just add another method. If there’s no package boundary, there’s no expression problem.justinpombrio, lobste.rs, 2025
The problem statement
The name was coined by Philip Wadler in 1998, in an email to a mailing list about generics for Java:
The Expression Problem is a new name for an old problem. The goal is to define a datatype by cases, where one can add new cases to the datatype and new functions over the datatype, without recompiling existing code, and while retaining static type safety (e.g., no casts).
Philip Wadler, The Expression Problem, 1998
In the same email he describes our table: the cases of the type are rows, the functions are columns. In a functional language the rows are fixed by the type declaration and adding columns is easy. In an object-oriented language it is the other way round: the class’s methods are fixed and adding subclasses is easy. The goal is to make both easy.
In Rust an enum corresponds to the functional approach, and a trait to the object-oriented one. The Rust Book says about enums:
This is a perfectly good solution when our interchangeable items are a fixed set of types that we know when our code is compiled. However, sometimes we want our library user to be able to extend the set of types that are valid in a particular situation.
What this means for Rust
Wadler stated the problem as a test for programming languages: can the type system express this kind of extensibility. Besides the rows and columns themselves, he set two conditions: do not recompile existing code, and keep static type safety.
The first condition: extend the table without touching code already written. As long as all the code is yours, this costs nothing: add a variant, fix every match, rebuild. That is why justinpombrio says there is no problem. It appears with other people’s libraries. You can write your own function with a match over the serde_json::Value enum, but you cannot add a variant to it. You can implement the std::fmt::Display trait for your type, but you cannot add a method to it.
The second condition: the compiler must report a missing cell. In Rust this is usually the case: if a match does not cover all variants, the code does not compile. But if the match has a _ arm that catches all remaining variants, a new variant silently lands in it, and the compiler says nothing. For example, when handling I/O errors by std::io::ErrorKind, the standard library’s enum of error kinds:
match err.kind() {
ErrorKind::NotFound => create_file(),
ErrorKind::PermissionDenied => request_access(),
_ => return Err(err),
}
That is why Matthias Zenger and Martin Odersky, in their 2005 paper, consider only solutions without such arms: in their words, defaults “transform type errors that would manifest statically into runtime exceptions that are thrown dynamically”.
Sometimes you cannot do without such an arm, and ErrorKind is one of those cases. Operating systems return many kinds of errors, and the standard library adds new variants over time. But if you add a variant to a public enum, every user’s match that covers all variants without _ stops compiling. The standard library promises not to break other people’s code, so ErrorKind is marked #[non_exhaustive]: the attribute means that more variants may appear, and the compiler requires a _ arm in every match outside the library. Since that arm is always there, a new variant breaks nothing.
From the expression problem’s point of view this is a compromise. The author of ErrorKind can add rows without breaking other people’s code, so the first of Wadler’s conditions holds. The second one is broken, and the compiler will not tell users about a new variant.
Solutions
There are solutions that let you extend the table in both directions, for example the Visitor pattern and Zenger and Odersky’s solutions in Scala; others are listed in the sources. All of them are noticeably more complex than a match or an impl. The article discussed on lobste.rs builds such a solution in Rust, and its conclusion is:
So, honestly, maybe you just shouldn’t do that.
purplesyringa, The expression problem and Rust, 2025
Conclusion
Honestly, I couldn’t come up with a final rule, but one thing is clear.
Every time you are about to abstract behaviour behind a trait or an enum wrapper, it is worth thinking about what the alternative would look like.
Sources
Discussions:
- Could enums be considered an anti-pattern?, users.rust-lang.org, 2017. The thread with answers from Klabnik, HadrienG, sfackler and withoutboats.
- Enum or trait object, r/rust, 2020. Discussion of the Possible Rust article “Enum or Trait Object”, where nivenkos writes about grouping code.
- The expression problem and Rust, lobste.rs, 2025. Discussion of the purplesyringa article.
Articles and documentation:
- purplesyringa, The expression problem and Rust, 2025. An attempt to solve the expression problem in Rust fully, and a discussion of why it may not be worth doing.
- Andrew Lilley Brinker, Enum or Trait Object, Possible Rust, 2020. A short guide: when an
enumis used inside a library, and when the library’s users need to extend the set of types. - The Rust Programming Language, 18.2. Trait objects, and when an
enumis enough. - The Rust Reference:
non_exhaustive.
Literature:
- Philip Wadler, The Expression Problem, 1998. The email in which the problem got its name.
- Matthias Zenger, Martin Odersky, Independently Extensible Solutions to the Expression Problem, 2005. Refined requirements and solutions in Scala.
- William R. Cook, Object-Oriented Programming Versus Abstract Data Types, 1990. The same table as a matrix of constructors and operations.
- Harold Abelson, Gerald Jay Sussman, Structure and Interpretation of Computer Programs, 2.4. Dispatching on type, data-directed programming and message passing; exercise 2.76.
- Wouter Swierstra, Data types à la carte, 2008. A solution in Haskell.
- Oleg Kiselyov, Typed Tagless Final Interpreters. The finally tagless approach.
- Bruno C. d. S. Oliveira, William R. Cook, Extensibility for the Masses: Practical Extensibility with Object Algebras, 2012. Object algebras.