Skip to content
Corrode Rust Consulting

Corrode Rust Consulting

corrode is a friendly Rust consulting company based in Düsseldorf, Germany. We help you build reliable software and ship it to production. We offer consulting, training, and development services for Rust projects. Provided by Matthias Endler.

corrode.dev
Corrode Rust ConsultingCorrode Rust Consulting
SOFTWARE AND DATA ENGINEERING

Why OTTO Chose Rust

I recently had the pleasure of interviewing Falk Woldmann Lu about OTTO’s recent migration of TypeScript Lambdas and Kotlin/Spring services to Rust. For readers outside Germany: OTTO is one of the country’s largest online retailers, with around 13 million active customers and €7.5 billion in gross merchandise value in the 2025/26 financial year. Falk is a Senior Fullstack Developer at OTTO and an Adjunct Rust Tutor at NORDAKADEMIE. ## Why Rust? Q: What was the recurring annoyance that made you start looking into Rust? We used to write our AWS Lambda functions in TypeScript (around 2022), and a couple of things bugged us about it. First, the build process was annoying because you had to bundle external dependencies. If you just bundled your whole node_modules directory, you also shipped build-time dependencies like esbuild or test runners. We used the serverless framework, but had to drop it at some point when they switched to a commercial license. Next, the churn in TS/JS tooling got on our nerves. It felt like we had to switch to the newest hot tool every two weeks or so, and nothing ever worked out of the box. The last thing was the language itself. TypeScript only gives you type safety at build time, so you have to be really careful about parsing data at runtime. Just casting your deserialized data with as Foo obviously isn’t enough, and we shot ourselves in the foot with that a couple of times. On top of that, the ecosystem was still pretty fractured between ESM and CommonJS back then, which caused even more headaches until everything ran smoothly. --- Q: But why Rust? You had plenty of less adventurous choices available like Kotlin or Go. Kotlin was the obvious candidate. We knew it well and it’s a good language, but most of our pain was around it. We actually tried running Kotlin on Lambda, and the tooling was about as painful as with TypeScript. Getting thin JARs to build was a struggle, and Spring Cloud Function was too buggy to rely on. Our Spring Boot services gave us their own headaches too, more on that later. Some of that is on Spring and not on Kotlin. In practice, though, Kotlin on the backend means the JVM and usually Spring. With Rust we kept the expressiveness and got a few things on top. Errors are values you have to handle, data is immutable by default, ownership is explicit, and resource usage is predictable because there’s no garbage collector. We could also use one language for Lambdas and long-running services. In the end, Rust fixed both problems we actually had: the painful Lambda tooling and the unpredictable runtime behavior. Q: If an experienced Go team had been sitting in your chairs, do you think they could reasonably have made the opposite decision? It really depends on what you focus on. At OTTO we mostly do brownfield product development, so for us it’s all about longevity. Go chose to keep the language small so you can ship fast. But most language complexity exists for a reason, and languages like Rust, Kotlin or Swift let us express more of our logic in code. That matters a lot to us, because we care about stability and predictability over many years. --- Falk Woldmann Lu specializes in Rust, distributed systems, cloud infrastructure, and DevOps. He's also a co-maintainer of httpmock, the HTTP mocking library mentioned in this interview. Photo: OTTO tech blog. ## The First Production Services Q: Take us back to the first Rust service you actually deployed. What were you nervous about and what happened once it went live? Rolling out our first Rust Lambda was exciting, since it was the first real test of our idea. The deployment itself was pretty unspectacular, though, because we started with a small internal Lambda. We could confirm right away that the Rust Lambda tooling works really well in production. Our hunch also held up: Lambdas are so high-level that a Rust Lambda doesn’t feel very different from a TypeScript one. The syntax is different, sure, but you get used to it quickly, and most of Rust’s more complex concepts like lifetime management just don’t come up. After those good experiences we migrated all our Lambdas. Execution time (warm and cold) and resource usage both went down a lot. That wasn’t a big deal for us, since our Lambdas weren’t particularly time-critical or expensive. Our first “real” web service in Rust was a different story. There’s a lot more to think about, like routing, scaling behavior and resource usage, so we were a lot more nervous. When we got our first Hello World back from the prototype, we were pretty ecstatic 😄 What helped with the actual migration was starting small. We took one piece of logic out of our big presentation service and rebuilt it in Rust. We had wanted to pull that logic out anyway, since it had little to do with presenting benefits, so it was a good candidate. The smaller scope kept the risk low and made it much easier to figure out how to set up a Rust web app properly. Q: Was there one graph, metric, or moment where the team thought: “Okay, this is cool”? That moment came when the service went live. The performance difference was massive. Our P99 roughly halved and resource usage dropped to a quarter, and that was with our first, pretty naive implementation. After a quick look at the code we removed an expensive clone on the hot path, which cut RAM usage in half again. That was great to watch and a really nice confirmation for us. > “Our first Rust code was pretty much Spring with Rust syntax.” ## Learning to Write Rust Q: You’ve said that some of your first Rust code was essentially Java or Spring thinking translated into Rust. What did you have to unlearn before you started writing Rust that actually felt like Rust? Controllers, services and repositories, all as structs, with dependency injection rebuilt on top. At first we used traits as the abstraction so we could swap in test implementations. We dropped that quickly, because generics and trait bounds for static dispatch spread through every signature and the code got really hard to read. We moved to faux, which can mock concrete structs without traits. That felt very familiar, basically Mockito for Rust. That layering is still there today, but we’re moving more and more towards Functional Core, Imperative Shell. Business logic goes into pure functions without side effects, which you can test without any mocks, and the I/O lives around them. So we need far fewer mocks now. What’s left we cover with integration tests against real components, like a containerized database or a real HTTP server via httpmock. Those give us a lot more confidence than a pile of mocks. The second big shift was actually using the type system: newtypes, “Parse, don’t validate”, enums for domain states, and typestate where it pays off. We studied this together with NORDAKADEMIE in a paper, using exactly this production code. My favorite example is the Dreson. At OTTO that’s a small grammar for describing a set of products. Our tag handler renders the little badges like “-20%” on product tiles, and it receives two Dresons per request: the context a benefit was configured for, and the context the customer is looking at right now. In the original code, both were plain strings. The validation was copy-pasted inline in the handler, couldn’t be tested on its own, and other handlers couldn’t reuse it. Worst of all, a validated Dreson was still just a String afterwards. Nothing told you whether it had been checked, so code that skipped validation or ran it three times compiled just fine. For the paper, we refactored it into a newtype: pub(super) struct Dreson(String); impl Dreson { pub fn from_string(dreson: String, exceptions: &[String]) -> anyhow::Result<Self> { if is_valid(&dreson) || exceptions.contains(&dreson) { Ok(Dreson(dreson)) } else { Err(anyhow::anyhow!("Invalid dreson format")) } } } It lives in its own private module, so the constructor is the only way to get one. Any function that takes a Dreson can trust the value is valid, and the signature tells you that without reading any docs. The validation is reusable and easy to test. In the refactoring, the handler’s cognitive complexity went from 17 to 8, and the runtime cost was too small to matter. For me, newtypes have the best cost/benefit ratio of any Rust pattern. The catch is that you have to use them consistently. As soon as someone goes back to the inner string, that code loses the guarantee. So we parse as early as we can, ideally right at the system boundary. I’m more careful with typestate. In the paper we also modeled the flow of our Detailview service as a state machine, so the steps can’t be called in the wrong order anymore. Testability and correctness got a lot better, and the cyclomatic complexity of the main function dropped from 17 to 3. You pay for that with boilerplate, though, and even our experts disagreed on whether it’s more readable. Typestate pays off most with lots of branching and lots of invariants. For a linear flow it’s often overkill. Q: What’s your favorite example of fighting the borrow checker only to finally realize that the compiler had exposed a problem in your design? Almost all our fights with the borrow checker happened when our code wasn’t very rusty, mostly early on. Lots of mutable state, lots of imperative code, data passed around and changed along the way. The fix was rarely a clever lifetime annotation. Usually we had to restructure how data flowed, and looking back, the compiler was right almost every time. One of our Lambdas for product returns is a good example of how we used to write code. It had two mutable lists for results and errors, and every function got them as &mut and modified them. That worked, but it was hard to tell what state the program was in at any point, and testing it was a pain. When we refactored it for the paper, the results and errors moved into the states themselves and each step became a pure function. Now that we write more idiomatic code, the borrow checker rarely gets in our way. Those fights were mostly a sign that our design was off. > “Rust made us better developers, and I notice that in other languages too.” --- ## Bringing the Team Along Q: What changed once the entire team had to work in Rust? The biggest help was learning Rust as a team. For the basics we used the usual resources: the Rust Book, Rustlings and 100 Exercises to Learn Rust. What made the difference was applying it to production code right away, with small, self-contained changes while pairing. At first the compiler feels like one more opponent. Once someone sits next to you and explains why it’s complaining, it turns into a safety net pretty quickly. We also ran a format we called “Rust Watch and Learn”, which had two parts. In the first, people from the team showed something they had recently learned or built in Rust. In the second, we discussed a blog post or video everyone had read or watched beforehand, very often one of Jon Gjengset’s. Since everyone came prepared, the discussion got into the details fast. Jon’s videos work really well for this because he explains why things are built the way they are. Jon Gjengset on Rust in Production Hear more from Jon in our Helsing episode of Rust in Production, where he talks about building safety-critical software in Rust. How fast were people productive? A lot faster than Rust’s reputation suggests. That lines up with Google’s numbers from 2022. More than two-thirds of respondents felt confident contributing to a Rust codebase within two months, and within four months more than half were as productive as in their previous language. Google found no evidence of a productivity penalty for Rust among the developers surveyed. It also helps that we mostly write fairly high-level CRUD code, which rarely touches the hard parts of Rust. Time until confident writing Rust. Source: Google's 2022 Rust survey. Q: Was there anyone on the team who initially disliked Rust and later changed their mind? There was skepticism in the team and also from managers and other stakeholders, which is fair. We were pitching a language that was pretty unusual for our kind of backend at the time. Two things won people over. The team actually learned Rust, and the learning curve turned out to be much less scary than expected. And the results were better: fewer bugs, better performance, lower costs. My favorite example is a colleague who was the loudest critic at the start. Today he’s one of our biggest Rust evangelists 😄 --- ## Reliability and Its Limits Q: What kinds of failures disappeared after the migration, and how much of that do you really attribute to Rust rather than to rewriting the system more carefully? The unpredictable runtime behavior is gone. In our old Kotlin/Spring services we kept seeing weird memory behavior, sometimes leaks, sometimes out-of-memory errors. We had to restart one service every day just to free up memory. The other big category was context and bean exceptions on startup. Those showed up a lot, even after minor Spring Boot updates, often because some starter pulled in something we had never configured ourselves. Spring is huge, it has grown over many years, and a lot of it is a black box. We were done with those surprises. We count anything that has a negative impact on customers as an incident. On the system level, meaning a service crashing, leaking memory, slowing down or failing to start, we haven’t had a single one since the migration. With Kotlin we had those quite a lot: after Spring Boot updates, from memory leaks, from bad performance. The services run very reliably now, memory usage is flat and predictable, and nobody has to restart services daily anymore. Logic bugs are a different story; I’ll get to those in a second. How much of that is Rust and how much is the careful rewrite? Both, to be fair. Some of it simply comes from dropping Spring. But the Rust ecosystem works very differently. There’s no auto-configuration and nothing magic happening at runtime. You build your service from small pieces you picked yourself, and if something isn’t in the code, it doesn’t happen. There’s also no garbage collector to tune, and errors show up in the types, so you have to handle them. Sure, we cleaned up a lot during the rewrite, but Rust pushed us towards those decisions. > “Rust is boring, and that's fantastic.” Q: And the important counter-question: what kinds of bugs does Rust do absolutely nothing to protect you from? Logic bugs, of course. We once showed the wrong headline on a customer benefit tile. The headline depends on whether you’re a guest, logged in, or also a member of OTTO Up, our loyalty program. Everything compiled, all the types lined up, and the customer still saw the wrong text. Here’s a simplified version I made up for this (our real code looks different), just to show how something like that can happen: fn headline(is_logged_in: bool, is_up_member: bool) -> &'static str { match (is_logged_in, is_up_member) { (true, true) => "Your Up benefit", (true, false) => "Join Up and save", (false, _) => "Log in to claim your benefit", } } // Compiles just fine, but the arguments are swapped. let text = headline(customer.is_up_member, customer.is_logged_in); That’s perfectly valid Rust. Two bools are interchangeable as far as the compiler cares, and the match is even exhaustive. This is where I think we could get more out of Rust. If you model the customer status as an enum, a whole class of mistakes goes away: enum CustomerStatus { Guest, LoggedIn, UpMember, } fn headline(status: &CustomerStatus) -> &'static str { match status { CustomerStatus::Guest => "Log in to claim your benefit", CustomerStatus::LoggedIn => "Join Up and save", CustomerStatus::UpMember => "Your Up benefit", } } Now there’s nothing to swap, and every status has exactly one headline. If someone adds a new status later, the compiler points you to every match that needs updating. What Rust can’t catch is me putting the Up member text in the LoggedIn arm. That compiles just as well. Only a human knows what the headline should say, so we still need tests. With typestate you could go even further. We’re not there yet, we’re still learning to use Rust to its full extent. Compared to Kotlin or TypeScript, Rust gives me better tools to rule out these mistakes step by step, and when I refactor, the compiler walks me through every place that’s affected. --- ## What Got Harder Q: In your blog post, you’ve spent a lot of time talking about what improved. So make the case against your own decision: what became harder, slower, more annoying, or simply less pleasant after moving to Rust? What I miss most is mocking from the JVM world. With Mockito or MockK you can mock pretty much anything in Kotlin and it just works. The JVM can generate bytecode at runtime. Rust has no reflection like that, so mocking concrete types relies on macros that rewrite your code at compile time. We use faux for that and it’s fine most of the time. You do notice the magic, though. It all happens at compile time, so it has never bitten us in production, but you feel it in the editor. In RustRover, autocompletion on mocked structs sometimes suggested the wrong things because the IDE got confused by the rewritten code. And some structures just don’t work. We ran into a case where a newtype around a mocked struct stopped compiling in tests, because faux needs all fields to be private. The maintainer says that’s by design. Fair enough, but it means the mocking tool decides how you structure your code. Mocking in Kotlin feels a lot more mature and stable. The funny thing is that this pushed us in a good direction. Because mocking in Rust hurts, we leaned even harder into the functional core and the integration tests I talked about earlier. Q: A bit of a loaded question, but what’s something that takes 30 lines in Rust that you still occasionally wish were five lines of Kotlin? With MockK, stubbing a dependency is a single line. With faux in Rust, it often means more setup, or restructuring your code so it can be mocked at all. --- ## When Not to Rewrite Q: Imagine another team at OTTO comes to you and says: “We saw what you did. We want to migrate our backend to Rust too.” What would you ask them before saying yes? That actually happened. My first question is always: what problems do you have with your current stack? Rust is very trendy right now, but FOMO is a bad reason to migrate. If a team is happy with Kotlin and Spring, their services run fine and nothing really hurts, a rewrite mostly means risk and effort. We had concrete problems, like painful tooling for our Lambdas and Spring behaving unpredictably at runtime. We picked Rust because it solved those. That said, I’ve become a lot more bullish on Rust as a default lately. For our kind of backend I see Rust clearly ahead of Java, Kotlin and Go, because none of them gives you an expressive type system, errors as values and no garbage collector all at once. And one of the big arguments against Rust, the learning curve, matters less every month. With agentic workflows you write fewer lines yourself. I’d even say Rust is one of the best languages for agents. The type system and the very descriptive compiler errors give an agent fast and precise feedback. It changes something, the compiler says exactly what’s wrong, it fixes it. Agents love that loop. What’s good for devs turns out to be good for agents too 😉 --- ## A Few Less Serious Questions All right. Short answers now. Q: Rust feature you initially hated but now love? macro_rules!. It was very confusing at first, but once you grok the syntax, it lets you get rid of a lot of boilerplate. For instance, we use it to generate lots of newtype structs. Q: Rust feature you still hate? 😉 Pin. I know there are good reasons for it to exist, but as a lowly app developer, every time I see it pop up somewhere, I know I’m in trouble 😆 Q: One thing Java or Kotlin still does better than Rust? The Kafka ecosystem is a lot more mature in the JVM world. In Rust, rdkafka is pretty much the only viable option, and it’s just a wrapper around the native C library. That causes some issues with compile times and cross-compilation. Q: Most underrated crate? typify and compio Q: How many crab-related items are currently visible in your office? We obviously have a crab plushie. It was actually caught attacking the mascot of our sister team, which builds a lot of OTTO-internal JVM tooling. Their mascot is a symbol for that. That was fun! Thanks for the interview, Falk. Planning a Rust migration? Thinking about introducing Rust into your backend? We help teams assess where Rust makes sense and migrate incrementally, without rewriting everything at once. Learn about our Rust consulting services.
GERMANYNORDAKADEMIEDRESON
this-week-in-rustThe Rust FoundationMy Very Best AI Slop | Vinnie | Substack
Corrode Rust ConsultingCorrode Rust Consulting
TRANSPORTATION AND LOGISTICS

Thinking in Traits

Rust favors composition over inheritance. I’m sure you’ve heard that before, but rarely does anyone take the time to explain what it means in practice. Also, why is this model the right choice for Rust? Let’s take a step back and look at an example: have you ever asked yourself why collect() works the way it does? let doubled: Vec<_> = numbers.iter().map(|x| x * 2).collect(); How does collect know to produce a Vec here? To answer that, let’s first look at the signature of Iterator::collect: fn collect<B: FromIterator<Self::Item>>(self) -> B where Self: Sized, { FromIterator::from_iter(self) } Note how it doesn’t mention Vec at all. In fact, it doesn’t “know” about any collection type or any other type, for that matter. The thing it does know is that whatever type you want must be capable of constructing itself from an iterator. And Vec<_> happens to be a type that does. Further note that we didn’t specify the element type of the vector. The compiler is clever enough to infer that from the context! The mechanism is the same for any other supported type, like hash maps, strings, or any custom collection type of your choosing as long as it implements FromIterator for the iterator’s item type. And what “collecting” means is also defined by the type itself. A String, for example, has the ability to collect characters: let chars = ['a', 'b', 'c']; let string: String = chars.iter().collect(); // "abc" And a HashMap can collect key-value pairs: let pairs = [("a", 1), ("b", 2), ("c", 3)]; // {"a": 1, "b": 2, "c": 3} let map: HashMap<_, _> = pairs.iter().cloned().collect(); It’s only fair to mention that interfaces can also express shared contracts. Here, two independently defined implementations connect through a shared item type. This is “composition through contracts”: Any of these iterators can feed into any of these collections as long as the bounds are satisfied. For example, HashSet<T> also requires T: Eq + Hash. Here, a producer yields values of some type T through the Iterator trait. On the other side, a collection implements FromIterator<T> to describe how it can build itself from those values. The shared item type T connects the two contracts, and collect() is the bridge between them. It requires only that the destination can be constructed from the items the iterator yields. In our first example, the Vec<_> annotation selects the destination type. Because Vec<T> implements FromIterator<T>, the compiler knows how to connect that destination to our iterator. collect() is the glue that passes the iterator to that implementation, which creates and fills the vector. Note how neither side needs to know the concrete type on the other side. The iterator doesn’t need to know how a vector stores its elements. And the vector doesn’t need to know where the items came from, only how to iterate over them. That means we can extend either side independently. A new iterator can feed existing collections, and a new collection implementing FromIterator<T> can accept existing iterators yielding T. We don’t need a separate conversion for every producer–collection pair. All we need is one implementation, and collect() is the glue that brings it all together. In simple Rust pseudocode, we can expand the calls step by step: // We call: iterator.collect::<Vec<T>>() // collect() delegates to: Vec::<T>::from_iter(iterator) // Which conceptually expands to: let mut vector = Vec::new(); while let Some(item) = iterator.next() { vector.push(item); } vector The value of an abstraction is the code that no longer needs to exist between its users. ## Boulevard of Broken Hierarchies Class inheritance models “is-a” relationships. In Java, for example, an SSLSocket is a subclass of Socket. An encrypted socket is still a socket, after all. But does every socket operation make sense for it? Socket.shutdownOutput() lets a TCP connection stop sending while continuing to receive, a feature called “half-closing.” Code using a socket might therefore do this: void finishSending(Socket socket) throws IOException { socket.shutdownOutput(); } On Android API levels 21 through 23, the platform’s SSLSocket implementations rejected this operation with UnsupportedOperationException. This caused a real crash in OkHttp 5.2.0. Modern OpenJDK supports TLS-aware shutdown, so this is a historical mismatch, not a universal limitation of TLS. Still, the Socket type exposed an operation without telling callers whether that implementation supported it. With composition, a TLS connection can hold a socket internally without exposing every operation on it. It can provide reading and writing, with a separate capability for half-closing where supported. We can reuse the transport without inheriting its entire interface. Simply replacing inheritance with interfaces—or traits—doesn’t fix a poorly chosen contract. What’s important is that the contract matches the capabilities of its implementations. ## Capability, Not Taxonomy Rust makes trait-based composition central to code reuse. In Rust, we ask what a type can do, not what it is. In other words, traits describe capabilities, not taxonomies. Here are simplified versions of two central I/O traits from the standard library: trait Read { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize>; } trait Write { fn write(&mut self, buf: &[u8]) -> io::Result<usize>; } Note how these are two independent traits. A type can implement Read, or Write, or both, or neither. You’re declaring which operations a type supports, without inheriting a bunch of unrelated methods. The capabilities are orthogonal. For example: - A byte slice (&[u8]) implements Read but not Write. - The Sink returned by std::io::sink() implements Write but not Read. - A TcpStream implements both. The trait implementation belongs to the type, not to a concrete value. Take std::fs::File, for example. It implements both Read and Write, but a file opened in read-only mode will still fail at runtime if you try to write to it. Even a file opened for writing can fail when the disk fills up. The trait implementation is a promise that the type supports those operations, but what it can’t do is guarantee that every operation will succeed at runtime. If you want to distinguish read-only and writable handles at compile time, you could define a ReadOnlyFile and a WritableFile and only implement the appropriate traits for each. That rules out unsupported operations in your API, but it still doesn’t make I/O infallible. ## Same Type, Different Capabilities Rust can express that a container has a capability only when its contents do. For example, Vec<T> implements Clone when T implements Clone. Thanks to this trick, we don’t end up with two different Vec types, one cloneable and one not. Here’s the same pattern for a small wrapper you could define yourself: struct Batch<T> { items: Vec<T>, } impl<T: Clone> Clone for Batch<T> { fn clone(&self) -> Self { Self { items: self.items.clone(), } } } A Batch<String> is cloneable because String is cloneable. A Batch<std::net::TcpStream> is not, since TcpStream does not implement Clone. If you were to call .clone() on that batch, the code wouldn’t compile. You can store non-cloneable items in a batch; you just can’t clone that batch. For this wrapper, you can use #[derive(Clone)] to generate the conditional implementation automatically. Note that the bound belongs on the implementation, not on Batch itself. Making your type cloneable requires T: Clone, but apart from that, Batch<T> is still a perfectly valid type for non-cloneable elements. The compiler works out which operations are available from the capabilities of the component types. A conditional implementation can also apply to every type that satisfies a trait bound as opposed to one particular wrapper. This is called a blanket implementation. For example, the standard library implements ToString for every type that implements Display: impl<T: std::fmt::Display + ?Sized> ToString for T { // Implementation omitted. } All you have to do to get a .to_string() method is implement Display for your type. The compiler automatically generates the ToString implementation for you. The rule applies even to types written long after the standard library itself. This is an elegant way to express a reusable implication between capabilities: “If a type can be displayed, it can be turned into a string.” The same idea appears in conversions. You might know that implementing From<T> for U automatically provides Into<U> for T through a blanket implementation. That’s why you normally implement From rather than writing the corresponding Into implementation yourself. ## Building Blocks From Building Blocks Conditional implementations also let us add behavior by wrapping one value in another. This is a different type of composition: “composition of values.” A wrapper holds another value and builds on its capabilities. Take our Read trait from earlier: - A File implements Read. - Wrapping it in a BufReader adds buffering, and the result still implements Read. - Calling .take(limit) on that reader limits how many bytes it yields, and the result still implements Read. File → BufReader<File> → Take<BufReader<File>> So a parser accepting R: Read doesn’t need separate support for files, buffered files, and length-limited buffered files. It just reads bytes! We can add buffering and a byte limit without teaching the parser about either. The parser doesn’t need to understand how its input was assembled. This works because each wrapper preserves the contract that the next piece needs. A BufReader<R> implements Read when R does, and so does Take<R>. The result of one composition becomes a building block for the next. You can see the same idea in iterator chains. - .map() produces a Map<I, F> iterator that applies a function to each item of the underlying iterator I. - .filter() produces a Filter<I, P> iterator that yields only the items of I that satisfy the predicate P. - .take() produces a Take<I> iterator that yields at most the first n items of I. Each type implements Iterator, so you can chain them. Writing your own iterator connects your type to this vast ecosystem of adapters. All you need is to provide the associated Item type and the next() method. map, filter, fold, and collect already have default implementations, available when their additional bounds are satisfied. This is how you reuse code without a base class. Default methods provide behavior within a trait you implement; blanket implementations can make another trait apply automatically. But adapters don’t have to be limited to a single, rigid contract either. They can provide rich, additional capabilities, too. For example, Map<I, F> implements DoubleEndedIterator when its input iterator does, and it does so with an appropriate trait bound on the mapping function: let values: Vec<_> = (0..5) .map(|n| n * 2) .rev() .collect(); assert_eq!(values, [8, 6, 4, 2, 0]); So because the map adapter has a conditional implementation for DoubleEndedIterator, it preserves the ability to iterate backward through the input. We’re not limited to basic iteration. And since we know the concrete iterator types, the compiler can optimize and inline the entire chain of adapters into a single loop. Optimized iterator code can perform comparably to a hand-written loop. So fully embracing iterator patterns has no runtime cost. ## To Enum Or To Trait? Hold on, Rust has another way to express “different kinds of things that are related”: enums! These are useful in situations where you know the full list of possibilities in advance. enum InputSource { File { path: PathBuf }, Http { url: String, timeout: Duration }, Stdin, } Enums are great if you almost always want to handle all of the variants in one place. Traits are the better model if different types implement the same behavior and you don’t know all of the types right now. In other words, enums are a closed set of variants while traits are an open set of implementations. You can’t add new variants to an enum without changing the enum definition. But traits enable the open/closed principle: you can add new implementations without modifying existing code. This allows other crates to extend your library without needing to modify your code. Imagine your library defines the Record and FetchError types, and you want to provide a way for users to fetch records from different sources. pub trait DataSource { fn fetch(&self) -> Result<Vec<Record>, FetchError>; } In your library, you implement DataSource for a PostgresSource and a RedisSource. But now, users can implement it for their own CsvFileSource or a CustomApiSource. Heck, you don’t even need to know these types exist. And yet, your contract still holds: any type that implements DataSource can be used to fetch records. The reverse is also true: an external contributor can define an extension trait and implement it for your type without you knowing about it. You can even do that with types from the standard library: trait ScreamingCase { fn screaming_case(&self) -> String; } impl ScreamingCase for String { fn screaming_case(&self) -> String { self.to_uppercase() } } As long as the trait is in scope, you can call the method on a String: let text = String::from("hello"); assert_eq!(text.screaming_case(), "HELLO"); No need to modify String or derive a ScreamingString subclass. This implementation is allowed because we define ScreamingCase in our crate. Rust’s coherence rules restrict implementations involving foreign traits and types. For example, we couldn’t implement the standard library’s Display trait directly for Vec<String>, since neither the trait nor the type is ours. This is composition at the level of behavior: we combine an existing type with an independently defined capability. The type and the trait don’t need to know about each other. The same type can implement other, unrelated traits, and each function can ask for just the capabilities it needs by means of trait bounds: // This works for any type that implements `ScreamingCase`. // E.g. why not implement it for `Vec<String>`, or `char` as well? fn scream<T: ScreamingCase>(value: &T) { println!("{}", value.screaming_case()); } This open-set/closed-set principle is a good way to think about when to use enums and when to use traits. But to be fair, the lines can blur a bit. An enum can also implement traits, and a library can restrict who implements a trait through a technique called a “sealed trait.” In application code, exhaustive enum checking can make refactoring easier because the compiler will tell you which match statements need to be updated when you add a new variant. Introduce a trait instead when you have a good reason to share a contract across types. ## Smaller Traits, Better Contracts The more unrelated responsibilities a trait combines, the harder it becomes to implement and reuse. Every implementer has to account for operations it may not need. Consider this application context: trait Context { fn fetch(&self, key: &str) -> Result<Record, Error>; fn store(&mut self, key: &str, record: &Record) -> Result<(), Error>; fn run(&mut self) -> Result<(), Error>; } Ask yourself: what concept does this trait capture? What contract does it enforce? It combines reading records, writing records, and running the application. Perhaps your application really needs one type to provide it all, but a function that copies records shouldn’t require its inputs to run an application. Let’s split the capabilities: trait Fetch { fn fetch(&self, key: &str) -> Result<Record, Error>; } trait Store { fn store(&mut self, key: &str, record: &Record) -> Result<(), Error>; } Now a read-only source can implement Fetch, a write-only destination can implement Store, and the execution runtime is left out. Your functions don’t need to know about the runtime either, and you can compose the exact capabilities you need: fn copy_record<S: Fetch, D: Store>( source: &S, destination: &mut D, key: &str, ) -> Result<(), Error> { let record = source.fetch(key)?; destination.store(key, &record) } Each of your types can implement either trait. Or both. This also explains how independent crates work with your types. Serde defines Serialize and Deserialize; your types implement them, often through derive macros. Serde’s serializers don’t need to know about your application’s structs in advance. They just use the shared contract: a type that implements Serialize can be serialized. Code becomes more composable as a consequence. If Serde decided to couple serialization and deserialization into a single trait, some use cases would be impossible to express. All of that is great for testing, too. We can test copy_record with a fake Fetch implementation and a fake Store implementation, without creating a runtime. The goal isn’t to make every trait contain exactly one method. Iterator has many methods, but they are all strictly related to the task of iterating over a sequence of values, and all but one (next()) have a default implementation. It’s fine to keep methods together when they describe the same contract, but if you’re unsure if callers need the independent capabilities, split your traits. ## Rules For Designing Traits Below are a couple of concrete tips around trait design. - When you approach a problem, ask what your code needs a type to be able to do. Often, an existing trait already expresses that. Check the standard library and popular crates first. And sometimes a concrete type or an enum is enough. - Write the code concretely first. If you find yourself copying similar implementations across different types, look for a shared contract. By then, you’ll have concrete examples to test your abstraction against. And when you do need a new trait, give it a contract you can explain in a single sentence. - Abstraction has a cost for readers. They may need to follow bounds and implementations across several files to understand a call. Sometimes that indirection hides details they shouldn’t need to care about. Sometimes it hides an important detail they should. - Trait-based abstractions in Rust often incur zero additional runtime overhead, but there is a compilation cost as well. The costs depend on how you use the trait. Generic code is usually monomorphized: the compiler generates code for the concrete types that use it. That permits static dispatch and inlining, but many instantiations can still increase compile time and binary size. For dyn-compatible traits, dynamic dispatch through dyn Trait lets the same caller operate on different implementations, but introduces indirection and can limit inlining. Not every trait supports this: FromIterator, for example, is not dyn-compatible. Keep these trade-offs in mind when you introduce a trait. There is no free lunch. ## Think Beyond the Parts Let’s come back to our collect() once more. So far, we’ve used the destination type to choose a collection. But it can also determine control flow. For example, we can decide to stop iterating on the first error or keep going and collect every result, including errors. I first learned about this from Karol Kuczmarski’s Iteration patterns for Result & Option, still one of my favorite Rust posts. Here it is in action: let input = ["10", "oops", "30"]; let every_result: Vec<Result<u32, _>> = input.iter().map(|s| s.parse()).collect(); let all_or_error: Result<Vec<u32>, _> = input.iter().map(|s| s.parse()).collect(); Note that in both cases, the iterator expressions are identical. The only thing that changes is the destination type: - Vec<Result<u32, _>> collects every parse result. - Result<Vec<u32>, _> returns the first error and stops advancing the iterator immediately. In the second case, "30" is never parsed. If every parse succeeds, the second version returns Ok containing the vector of values. This behavior comes from the standard library’s FromIterator implementation for Result. Here’s a stub of that implementation: impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E> where V: FromIterator<A>, { // Implementation omitted. } What this says is: > An iterator of Result<A, E> values can be collected into a Result<V, E>, as long as V can collect values of type A. The V: FromIterator<A> bound means that V could be a Vec<A> or any other type that can collect those values. collect() itself doesn’t need to know any of this: it just calls the destination type’s FromIterator implementation. See how all of those pieces fit together? That’s the real payoff when you think in traits. A single implementation can connect a type to an entire ecosystem of algorithms, adapters, and collections. A few carefully crafted capabilities can combine in ways their authors never imagined. That makes the whole greater than the sum of its parts. And that’s just great API design.
RUST
yoshuawuyts
Corrode Rust ConsultingCorrode Rust Consulting
CONSUMER ELECTRONICS AND ROBOTICS

Local Reasoning in Rust

A good metric for ergonomic API design is how much of a program you have to keep in your head at once to know what’s going on. It’s empowering if you can understand a function by its type signature and get immediate feedback on whether you used it correctly. Other times, it feels like you’re a code archaeologist: Was this value validated before? Is it safe to retry this call? Can this panic? Bad APIs make local reasoning hard. “Local reasoning” here means being able to understand a piece of code from a limited amount of surrounding context and the contracts of the APIs it uses. The main point is that you can rely on those contracts without additional knowledge of the implementation. What makes Rust feel different from other languages is the ability to encode invariants in the type system and do so at zero cost. That’s a rare combination. Once you notice this “local reasoning principle”, you’ll see it everywhere in Rust’s standard library: through the use of Result and Option, borrows marked with &, enums to represent a closed set of possibilities, or explicit unsafe functions. This information is always visible in every function signature. A simple way to apply this mindset yourself is to check if your function signatures communicate as much information as possible to the caller. Maybe show the signature to a friend or colleague and ask them to explain what it does. It can be eye-opening. Let’s look at a few examples. ## Put Relationships in the Signature Consider this function signature: fn first_line(text: &str) -> Option<&str> Before even looking at the implementation, we already know that the function takes a borrowed input and may have no output. (Or, rather, it may return None.) Actually, if you know Rust’s lifetime elision rules, you know that the real signature is: fn first_line<'text>(text: &'text str) -> Option<&'text str> The input is tied to the output. That implies that the caller can’t keep using the returned string after the borrow of text has ended. And by extension, the function can’t return a temporary string either. The function is not making any long-lived allocations. That’s a lot of useful information for just one function header! All of that is great, but equally important, there are a few “implicit” assumptions that the signature does not guarantee. Take the function name: it suggests that the function returns “the first line of something.” However, the type system does not enforce that. It could return the last line for all we know, and the signature would be identical. The function header also won’t tell us whether anything is logged, how it performs, or whether it panics. Rust is often described as an explicit language. Yet it also uses type inference, lifetime elision, automatic borrowing of method receivers, and implicit coercions. That’s because writing everything out would make many programs harder to read. What you should make explicit depends on your context. A good rule of thumb when designing an API is to look for relationships that callers would otherwise have to keep in their heads. Does your function really take any &str, or does it expect a string that has been validated in some way? For example, is an empty string valid input? What does None mean in the return value? Should it be treated as an error, or is it a valid case? Should it be a Result instead? Good function signatures tell a story about the relationships between inputs and outputs. ## Keep Consequential Choices Visible Consider these two calls, where text is a String: inspect(&text); consume(text); The first call borrows text while the second one moves it. Now let’s look at the context of the borrowed call: fn inspect(text: &str) { println!("{text}"); } let text = String::from("hello"); inspect(&text); The compiler applies a deref coercion automatically. I think that’s a good compromise: the ownership decision is still visible, but the compiler handles the bookkeeping. Some people argue that we could go one step further. Why not automatically borrow an owned argument in an ordinary function call? We could then write inspect(text) instead of inspect(&text), which seems convenient. But, as always, there’s a cost to convenience. Saving the & would remove information readers currently get from the expression itself: that the value does not move.[1] Convenience does not always mean better ergonomics. This gives us a way to judge our own conveniences, too. Implementing Deref for a wrapper makes its target’s methods available implicitly. That’s convenient. But it’s a slippery slope. It can lead to leaky abstractions, where a wrapper type is treated as if it were the underlying type, but is not quite the same. Suppose a UserId stores a String. You might consider implementing Deref<Target = str> for it, so that callers can use it as if it were a &str. Now you expose the whole string interface through Deref. You implicitly allow callers to treat the identifier as text, sidestepping all type invariants. Instead, an explicit as_str() leaves a visible point where the identifier is treated as text. It also lets your UserId newtype have an API of its own. Interaction with user IDs becomes more deliberate. Use Deref only when the wrapper transparently behaves like its target and dereferencing is cheap and unsurprising. The standard library agrees. ## Give Names a Purpose Take a look at this function signature: fn visit<F: FnMut(&str)>(callback: F) Here, we introduce a name, F, give it a bound of FnMut(&str), and then use it exactly once for callback. I think that signature would be clearer if we put the requirement right next to where it’s used: fn visit(callback: impl FnMut(&str)) Now you can read the signature from left to right. This saves you from jumping back and forth just to figure out what F means. One less thing to keep in your head while reading.[2] Now, I’m not saying that version two is always better. For example, it can be helpful to keep generics separate from the rest of the signature when the generic type is used in multiple places: fn choose<T>(first: T, second: T, take_first: bool) -> T { if take_first { first } else { second } } Here, T tells us that both arguments as well as the return value have the same type. The same thinking applies to return types: fn nonempty(lines: &[String]) -> impl Iterator<Item = &str> { lines.iter().map(String::as_str).filter(|s| !s.is_empty()) } impl Iterator<Item = &str> tells the caller what they can do with the result, namely iterate over borrowed strings. (Besides, if you tried writing out the concrete return type of that function, it would be unnecessarily long and complicated.) Ask yourself: does naming this type help the caller understand something? ## Ownership Beyond Memory We usually learn about ownership in the context of memory. But the same rules apply in other situations. Take file descriptors, for example. On Unix, a raw file descriptor is just an integer. That integer doesn’t tell you whether the descriptor is still open, or who’s responsible for closing it. Worse, once it’s closed, the operating system can reuse the number for something else. Consider these two signatures, using types from std::os::fd: fn inspect(fd: RawFd) -> std::io::Result<()> fn inspect(fd: BorrowedFd<'_>) -> std::io::Result<()> The first signature only gives us an integer. RawFd is literally just an alias for c_int. But that descriptor might already be closed. Those “time-of-check to time-of-use” bugs are a common pitfall of safe Rust. The second guarantees that the descriptor remains open for the duration of the borrow.[3] The caller keeps its owner alive, and Rust checks that relationship when we borrow from a File: use std::fs::File; use std::os::fd::AsFd; let file = File::open("notes.txt")?; inspect(file.as_fd())?; Now the compiler can help! You can’t drop file and then keep using the descriptor borrowed from it in safe Rust. You no longer need to search through the code to check whether someone closed it earlier. But what if our function should really take ownership of the file descriptor? Use OwnedFd instead. When the OwnedFd is dropped, the descriptor is closed automatically, so the caller doesn’t have to remember to do it. In a sense, memory and file descriptors share a similar set of types with different guarantees: | Memory | File descriptors | Use Case | | ----------- | ---------------- | ------------------------------------------------------------------------------------- | | Box<T> | OwnedFd | “I want to own this resource and close it when I’m done.” | | &T | BorrowedFd<'a> | “I want to borrow this resource for a limited time.” | | Raw pointer | RawFd | “I want to use this resource, but I don’t know who owns it or how long it will live.” | Lock guards are another example. { let _guard = lock.lock(); // do cool things with lock } // We no longer have access to the lock here, because `_guard` was dropped. If you can access the data, you hold the lock. You don’t have to “trace the program back” to an earlier lock() call and check every path for an unlock. In C, that’s very much the case and easy to get wrong. Of course, these types only guarantee what they encode. A BorrowedFd keeps track of one borrow, but it doesn’t guarantee exclusivity over the underlying resource. That means another process might still be writing to the same file. But in general, you can stop relying on callers to remember the provenance of a resource. That’s a much stronger guarantee than simply saying “keep this open until you’re done” in your API documentation. Raw handles are still necessary at a low-level boundary, but you don’t have to pass them through your entire application. The lesson is that you can encapsulate ownership information in your own types and provide a safe wrapper around an unsafe API. ## Explain Who Is Responsible Sometimes things are truly outside of Rust’s control. In that case, the safety responsibility shifts to the user. We use unsafe APIs to make that inversion of responsibility explicit. In Rust, there are two different responsibilities, which share the same keyword: - An unsafe fn says: “Before you call me, you MUST establish these conditions. This is your responsibility.” - An unsafe block means you’re responsible for satisfying the conditions of the unsafe operations inside the block.[4] The difference is that an unsafe fn sets safety conditions that its caller must meet, while an unsafe block marks where the person writing the code claims that each unsafe operation’s safety conditions have been met. In both cases, it is good practice to add safety comments to make readers aware of these conditions. Here’s how that could look in practice: /// # Safety /// `index` must be less than `values.len()`. unsafe fn element_unchecked(values: &[u8], index: usize) -> u8 { // SAFETY: The caller guarantees that `index` is in bounds. unsafe { *values.get_unchecked(index) } } In general, you should use get(index) instead to handle the None case, but this example illustrates how to document safety obligations. Since the type system can’t check the safety conditions, it’s your obligation to keep the documentation up to date. Suppose someone adds another unsafe operation to this function later. Does knowing that index is in bounds make that operation safe, too? Maybe. You have to check and potentially update your docs. Quick tip: when you write a safety comment, explain why the operation is safe. “This is safe” doesn’t help the next person, but “The caller guarantees that the index is in bounds” gives them something they can check. Another tip: in Rust 2024, unsafe operations inside unsafe functions warn by default unless you put them in an explicit unsafe block. You can enforce that with #![deny(unsafe_op_in_unsafe_fn)]. ## Don’t Make Callers Do Your Work You’ve probably heard the advice to panic for programmer errors and return Result for recoverable failures. That’s reasonable, but who decides what counts as a programmer error? You do, when you design the API.[5] Consider the difference between indexing and get: let item = items[index]; let item = items.get(index); If you use indexing, you need to know that the index is valid to avoid a panic. With get, you can try the lookup and handle None if it fails. Remember that both are safe Rust: an invalid index doesn’t cause undefined behavior in either case. Now suppose the index comes from user input. Is an out-of-bounds index really a bug in your program? Or is it something you should expect and handle? One escape hatch is to make every caller check the index before calling your function. A strict precondition might make your work simpler, but think about your users. Before you document another thing the caller “must” do, ask whether your API could handle it instead. For example, you could return an Option and let callers decide what to do next. That doesn’t mean you should avoid indexing altogether. If an index is indeed valid by construction, indexing can express that assumption directly. A panic then means there’s a bug in your API. It’s probably fine to panic in that case, instead of introducing undefined behavior. And often it’s possible to sidestep these issues entirely. For example, if you need to visit each element of a collection, use an iterator. This way, you don’t have to worry about indices at all. ## Decide What You Want to Promise Another mental model for building great APIs is to think about what you want to guarantee to your users. Remember Hyrum’s Law: > With a sufficient number of users of an API, > it does not matter what you promise in the contract: > all observable behaviors of your system > will be depended on by somebody. With that in mind, think about what happens when you try to change your API. For example, users can match on every variant of your public enum. They can’t forget a case, because the compiler will warn them about it. That’s local reasoning at work, which is great. But on the flip side, it also means that you can’t add a variant without breaking their code. You’ve broken a guarantee they depended on. To prevent that, mark your enum as #[non_exhaustive] so you can add variants later: #[non_exhaustive] pub enum ServiceError { Unavailable, Rejected, } In that case, users have to include a fallback when matching the enum.[6] You’ve pushed the responsibility to the call site, which is likely the better place to decide what to do with an unexpected variant. Exhaustive matching keeps working inside your own crate. Should you add #[non_exhaustive] to every public enum just in case? No. If the set of possibilities really is closed, exhaustive matching gives users a useful guarantee. Don’t take it away without a reason. Examples of closed sets include days of the week, months of the year, or the suits of a deck of cards: pub enum Suit { Hearts, Diamonds, Clubs, Spades, } If you make this enum non-exhaustive, users can’t use your crate to implement a card game without having to handle an impossible case. The awkward middle ground is a set that looks closed but really isn’t. HTTP status codes are a good example: mapping all the standard codes doesn’t mean you’re safe from a vendor inventing their own codes. This caused a real problem in http-types: a user reported that constructing a response with Cloudflare’s custom status codes panicked because the library’s StatusCode enum couldn’t represent them. #[non_exhaustive] doesn’t solve that problem by itself. It lets you add additional variants in the future, but it doesn’t allow users to represent unknown codes today. How about we add Unregistered(u16)? #[non_exhaustive] pub enum Status { Ok, NotFound, // Other known status codes we can't name yet... Unregistered(u16), } Now users can handle codes which don’t have a name yet: fn is_early_hints(status: Status) -> bool { match status { Status::Unregistered(103) => true, _ => false, } } But that introduces another compatibility trap. Suppose a later release adds an EarlyHints variant and starts returning it for code 103. The function now returns false for the same HTTP status code. The code still compiles, but its behavior has changed. I recommend reading “Pattern Matching and Backwards Compatibility” by Sean McArthur, the author of the http crate, about how even an enum with a catch-all variant can make promises you didn’t intend. The escape hatch for the http crate was to make StatusCode an opaque struct with associated constants for the known codes like StatusCode::OK. Users can then construct values from numeric codes, even when the library doesn’t have a name for them: use http::StatusCode; let status = StatusCode::from_u16(599).unwrap(); assert_eq!(status.as_u16(), 599); They can still match on familiar codes, but they have to include a fallback. And they can handle an unnamed code by inspecting its numeric value: use http::StatusCode; fn describe(status: StatusCode) -> &'static str { match status { StatusCode::OK => "success", code if code.as_u16() == 103 => "early hints", _ => "some other status", } } That’s pretty clever, because adding a new constant like StatusCode::EARLY_HINTS assigns a name to a value without changing the underlying representation, and numeric checks continue to work. So before making something public, ask yourself: am I willing to uphold this guarantee forever? This applies to your entire public API, including enums and public fields inside structs. Changing things later can break user code. From their perspective, it was part of the API all along. ## Try It on Your Own APIs I suggest you put that advice into practice. Pick a function in your codebase and look at it from the caller’s perspective. What do you have to know to use it correctly? Can you get that information from the signature, or do you have to read the implementation first? Look for instructions in the documentation that the compiler could help enforce. Instead of writing “keep this resource alive”, maybe you can return a borrowed type. “Only pass validated text” might become a newtype with some validation in the constructor. You don’t have to follow every single suggestion in this article, either. The goal is to make your API easier to understand and harder to misuse. Where to go from here Want a second pair of eyes on your Rust APIs? I can help you put these patterns to work in your codebase. - For your team. Training, code review, and architecture support to ship Rust with confidence. - For yourself. 1-on-1 mentorship for Rust design, architecture, and code review on real projects. 1. RFC 241: Deref coercions discusses why automatically borrowing arguments would make local reasoning harder. ↩ 2. RFC 1951: Expand impl Trait explains ergonomics in terms of how much you have to keep in your head, and discusses who chooses the concrete type. ↩ 3. RFC 3128: I/O safety explains the analogy between raw handles and raw pointers, and introduces owned and borrowed handle types. ↩ 4. RFC 2585: Unsafe blocks in unsafe functions separates defining safety obligations from satisfying them. The Rust 2024 edition guide covers the lint’s current default. ↩ 5. RFC 236: Error conventions recommends expressing contracts through types where possible, and using Result or Option when a stricter contract is hard to justify. The discussion of task failure predates Rust 1.0; the advice about API contracts is the relevant part here. ↩ 6. RFC 2008: Non-exhaustive enums and structs discusses exhaustive matching and the freedom to add new variants. ↩
RUST
yoshuawuytsRust InternalsLinux Compatible
Corrode Rust ConsultingCorrode Rust Consulting
SOFTWARE AND DATA ENGINEERING

Practical Rust API Design

A good metric for ergonomic systems design is how much of a program you have to keep in your head at once to know what’s going on. It’s empowering if you can understand a function by its type signature and get immediate feedback on whether you used it correctly. Other times, it feels like you’re a code archaeologist: Was this value validated before? Is it safe to retry this call? Can this panic? Bad APIs make local reasoning hard. “Local reasoning” here means being able to understand a piece of code from a limited amount of surrounding context and the contracts of the APIs it uses. The main point is that you can rely on those contracts without additional knowledge of the implementation. What makes Rust feel different from other languages is the ability to encode invariants in the type system and do so at zero cost. The combination of both properties is rare. Once you notice this “local reasoning principle”, you’ll see it everywhere in Rust’s standard library: through the use of Result and Option, borrows marked with &, enums to represent a closed set of possibilities, or explicit unsafe blocks. This information is always visible in every function signature. A simple way to apply this mindset yourself is to check if your function signatures communicate as much information as possible to the caller. Maybe show the signature to a friend or colleague and ask them to explain what it does. It can be eye-opening. Let’s look at a few examples. ## Put Relationships in the Signature Consider this function signature: fn first_line(text: &str) -> Option<&str> Before even looking at the implementation, we already know that the function takes a borrowed input and may have no output. (Or, rather, it may return None.) Actually, if you know Rust’s lifetime elision rules, you know that the real signature is: fn first_line<'text>(text: &'text str) -> Option<&'text str> The input is tied to the output. That implies that the caller can’t keep using the returned string after the borrow of text has ended. And by extension, the function can’t return a temporary string either. The function is not making any long-lived allocations. That’s a lot of useful information for just one function header! All of that is great, but equally important, there are a few “implicit” assumptions that the signature does not guarantee. Take the function name: it suggests that the function returns “the first line of something.” However, the type system does not enforce that. It could return the last line for all we know, and the signature would be identical. The function header also won’t tell us whether anything is logged, how it performs, or whether it panics. Rust is often described as an explicit language. Yet it also uses type inference, lifetime elision, automatic borrowing of method receivers, and implicit coercions. That’s because writing everything out would make many programs harder to read. What you should make explicit depends on your context. A good rule of thumb when designing an API is to look for relationships that callers would otherwise have to keep in their heads. Does your function really take any &str, or does it expect a string that has been validated in some way? For example, is an empty string valid input? What does None mean in the return value? Should it be treated as an error, or is it a valid case? Should it be a Result instead? Good function signatures tell a story about the relationships between inputs and outputs. ## Keep Consequential Choices Visible Consider these two calls, where text is a String: inspect(&text); consume(text); The first call borrows text while the second one moves it. Now let’s look at the context of the borrowed call: fn inspect(text: &str) { println!("{text}"); } let text = String::from("hello"); inspect(&text); The compiler applies a deref coercion automatically. I think that’s a good compromise: the ownership decision is still visible, but the compiler handles the bookkeeping. Some people argue that we could go one step further. Why not automatically borrow an owned argument in an ordinary function call? We could then write inspect(text) instead of inspect(&text), which seems convenient. But, as always, there’s a cost to convenience. Saving the & would remove information readers currently get from the expression itself: that the value does not move.[1] Convenience does not always mean better ergonomics. This gives us a way to judge our own conveniences, too. Implementing Deref for a wrapper makes its target’s methods available implicitly. That’s convenient. But it’s a slippery slope. It can lead to leaky abstractions, where a wrapper type is treated as if it were the underlying type, but is not quite the same. Suppose a UserId stores a String. You might consider implementing Deref<Target = str> for it, so that callers can use it as if it were a &str. Now you expose the whole string interface through Deref. You implicitly allow callers to treat the identifier as text, sidestepping all type invariants. Instead, an explicit as_str() leaves a visible point where the identifier is treated as text. It also lets your UserId newtype have an API of its own. Interaction with user IDs becomes more deliberate. Use Deref only when the wrapper transparently behaves like its target and dereferencing is cheap and unsurprising. The standard library agrees. ## Give Names a Purpose Take a look at this function signature: fn visit<F: FnMut(&str)>(callback: F) Here, we introduce a name, F, give it a bound of FnMut(&str), and then use it exactly once for callback. I think that signature would be clearer if we put the requirement right next to where it’s used: fn visit(callback: impl FnMut(&str)) Now you can read the signature from left to right. This saves you from jumping back and forth just to figure out what F means. One less thing to keep in your head while reading.[2] Now, I’m not saying that version two is always better. For example, it can be helpful to keep generics separate from the rest of the signature when the generic type is used in multiple places: fn choose<T>(first: T, second: T, take_first: bool) -> T { if take_first { first } else { second } } Here, T tells us that both arguments as well as the return value have the same type. The same thinking applies to return types: fn nonempty(lines: &[String]) -> impl Iterator<Item = &str> { lines.iter().map(String::as_str).filter(|s| !s.is_empty()) } impl Iterator<Item = &str> tells the caller what they can do with the result, namely iterate over borrowed strings. (Besides, if you tried writing out the concrete return type of that function, it would be unnecessarily long and complicated.) Ask yourself: does naming this type help the caller understand something? ## Ownership Beyond Memory We usually learn about ownership in the context of memory. But the same rules apply in other situations. Take file descriptors, for example. On Unix, a raw file descriptor is just an integer. That integer doesn’t tell you whether the descriptor is still open, or who’s responsible for closing it. Worse, once it’s closed, the operating system can reuse the number for something else. Consider these two signatures, using types from std::os::fd: fn inspect(fd: RawFd) -> std::io::Result<()> fn inspect(fd: BorrowedFd<'_>) -> std::io::Result<()> The first signature only gives us an integer. RawFd is literally just an alias for c_int. But that descriptor might already be closed. Those “time-of-check to time-of-use” bugs are a common pitfall of safe Rust. The second guarantees that the descriptor remains open for the duration of the borrow.[3] The caller keeps its owner alive, and Rust checks that relationship when we borrow from a File: use std::fs::File; use std::os::fd::AsFd; let file = File::open("notes.txt")?; inspect(file.as_fd())?; Now the compiler can help! You can’t drop file and then keep using the descriptor borrowed from it in safe Rust. You no longer need to search through the code to check whether someone closed it earlier. But what if our function should really take ownership of the file descriptor? Use OwnedFd instead. When the OwnedFd is dropped, the descriptor is closed automatically, so the caller doesn’t have to remember to do it. In a sense, memory and file descriptors share a similar set of types with different guarantees: | Memory | File descriptors | Use Case | | ----------- | ---------------- | ------------------------------------------------------------------------------------- | | Box<T> | OwnedFd | “I want to own this resource and close it when I’m done.” | | &T | BorrowedFd<'a> | “I want to borrow this resource for a limited time.” | | Raw pointer | RawFd | “I want to use this resource, but I don’t know who owns it or how long it will live.” | Lock guards are another example. { let _guard = lock.lock(); // do cool things with lock } // We no longer have access to the lock here, because `_guard` was dropped. If you can access the data, you hold the lock. You don’t have to “trace the program back” to an earlier lock() call and check every path for an unlock. In C, that’s very much the case and easy to get wrong. Of course, these types only guarantee what they encode. A BorrowedFd keeps track of one borrow, but it doesn’t guarantee exclusivity over the underlying resource. That means another process might still be writing to the same file. But in general, you can stop relying on callers to remember the provenance of a resource. That’s a much stronger guarantee than simply saying “keep this open until you’re done” in your API documentation. Raw handles are still necessary at a low-level boundary, but you don’t have to pass them through your entire application. The lesson is that you can encapsulate ownership information in your own types and provide a safe wrapper around an unsafe API. ## Explain Who Is Responsible Sometimes things are truly outside of Rust’s control. In that case, the safety responsibility shifts to the user. We use unsafe APIs to make that inversion of responsibility explicit. In Rust, there are two different responsibilities, which share the same keyword: - An unsafe fn says: “Before you call me, you MUST establish these conditions. This is your responsibility.” - An unsafe block means you’re responsible for satisfying the conditions of the unsafe operations inside the block.[4] The difference is that an unsafe fn sets safety conditions that its caller must meet, while an unsafe block marks where the person writing the code claims that each unsafe operation’s safety conditions have been met. In both cases, it is good practice to add safety comments to make readers aware of these conditions. Here’s how that could look in practice: /// # Safety /// `index` must be less than `values.len()`. unsafe fn element_unchecked(values: &[u8], index: usize) -> u8 { // SAFETY: The caller guarantees that `index` is in bounds. unsafe { *values.get_unchecked(index) } } In general, you should use get(index) instead to handle the None case, but this example illustrates how to document safety obligations. Since the type system can’t check the safety conditions, it’s your obligation to keep the documentation up to date. Suppose someone adds another unsafe operation to this function later. Does knowing that index is in bounds make that operation safe, too? Maybe. You have to check and potentially update your docs. Quick tip: when you write a safety comment, explain why the operation is safe. “This is safe” doesn’t help the next person, but “The caller guarantees that the index is in bounds” gives them something they can check. Another tip: in Rust 2024, unsafe operations inside unsafe functions warn by default unless you put them in an explicit unsafe block. You can enforce that with #![deny(unsafe_op_in_unsafe_fn)]. ## Don’t Make Callers Do Your Work You’ve probably heard the advice to panic for programmer errors and return Result for recoverable failures. That’s reasonable, but who decides what counts as a programmer error? You do, when you design the API.[5] Consider the difference between indexing and get: let item = items[index]; let item = items.get(index); If you use indexing, you need to know that the index is valid to avoid a panic. With get, you can try the lookup and handle None if it fails. Remember that both are safe Rust: an invalid index doesn’t cause undefined behavior in either case. Now suppose the index comes from user input. Is an out-of-bounds index really a bug in your program? Or is it something you should expect and handle? One escape hatch is to make every caller check the index before calling your function. A strict precondition might make your work simpler, but think about your users. Before you document another thing the caller “must” do, ask whether your API could handle it instead. For example, you could return an Option and let callers decide what to do next. That doesn’t mean you should avoid indexing altogether. If an index is indeed valid by construction, indexing can express that assumption directly. A panic then means there’s a bug in your API. It’s probably fine to panic in that case, instead of introducing undefined behavior. And often it’s possible to sidestep these issues entirely. For example, if you need to visit each element of a collection, use an iterator. This way, you don’t have to worry about indices at all. ## Decide What You Want to Promise Another mental model for building great APIs is to think about what you want to guarantee to your users. Remember Hyrum’s Law: > With a sufficient number of users of an API, > it does not matter what you promise in the contract: > all observable behaviors of your system > will be depended on by somebody. With that in mind, think about what happens when you try to change your API. For example, users can match on every variant of your public enum. They can’t forget a case, because the compiler will warn them about it. That’s local reasoning at work, which is great. But on the flip side, it also means that you can’t add a variant without breaking their code. You’ve broken a guarantee they depended on. To prevent that, mark your enum as #[non_exhaustive] so you can add variants later: #[non_exhaustive] pub enum ServiceError { Unavailable, Rejected, } In that case, users have to include a fallback when matching the enum.[6] You’ve pushed the responsibility to the call site, which is likely the better place to decide what to do with an unexpected variant. Exhaustive matching keeps working inside your own crate. Should you add #[non_exhaustive] to every public enum just in case? No. If the set of possibilities really is closed, exhaustive matching gives users a useful guarantee. Don’t take it away without a reason. Examples of closed sets include days of the week, months of the year, or the suits of a deck of cards: pub enum Suit { Hearts, Diamonds, Clubs, Spades, } If you make this enum non-exhaustive, users can’t use your crate to implement a card game without having to handle an impossible case. The awkward middle ground is a set that looks closed but really isn’t. HTTP status codes are a good example: mapping all the standard codes doesn’t mean you’re safe from a vendor inventing their own codes. This caused a real problem in http-types: a user reported that constructing a response with Cloudflare’s custom status codes panicked because the library’s StatusCode enum couldn’t represent them. #[non_exhaustive] doesn’t solve that problem by itself. It lets you add additional variants in the future, but it doesn’t allow users to represent unknown codes today. How about we add Unregistered(u16)? #[non_exhaustive] pub enum Status { Ok, NotFound, // Other known status codes we can't name yet... Unregistered(u16), } Now users can handle codes which don’t have a name yet: fn is_early_hints(status: Status) -> bool { match status { Status::Unregistered(103) => true, _ => false, } } But that introduces another compatibility trap. Suppose a later release adds an EarlyHints variant and starts returning it for code 103. The function now returns false for the same HTTP status code. The code still compiles, but its behavior has changed. I recommend reading “Pattern Matching and Backwards Compatibility” by Sean McArthur, the author of the http crate, about how even an enum with a catch-all variant can make promises you didn’t intend. The escape hatch for the http crate was to make StatusCode an opaque struct with associated constants for the known codes like StatusCode::OK. Users can then construct values from numeric codes, even when the library doesn’t have a name for them: use http::StatusCode; let status = StatusCode::from_u16(599).unwrap(); assert_eq!(status.as_u16(), 599); They can still match on familiar codes, but they have to include a fallback. And they can handle an unnamed code by inspecting its numeric value: use http::StatusCode; fn describe(status: StatusCode) -> &'static str { match status { StatusCode::OK => "success", code if code.as_u16() == 103 => "early hints", _ => "some other status", } } That’s pretty clever, because adding a new constant like StatusCode::EARLY_HINTS assigns a name to a value without changing the underlying representation, and numeric checks continue to work. So before making something public, ask yourself: am I willing to uphold this guarantee forever? This applies to your entire public API, including enums and public fields inside structs. Changing things later can break user code. From their perspective, it was part of the API all along. ## Try It on Your Own APIs I suggest you put that advice into practice. Pick a function in your codebase and look at it from the caller’s perspective. What do you have to know to use it correctly? Can you get that information from the signature, or do you have to read the implementation first? Look for instructions in the documentation that the compiler could help enforce. Instead of writing “keep this resource alive”, maybe you can return a borrowed type. “Only pass validated text” might become a newtype with some validation in the constructor. You don’t have to follow every single suggestion in this article, either. The goal is to make your API easier to understand and harder to misuse. Where to go from here Want a second pair of eyes on your Rust APIs? I can help you put these patterns to work in your codebase. - For your team. Training, code review, and architecture support to ship Rust with confidence. - For yourself. 1-on-1 mentorship for Rust design, architecture, and code review on real projects. 1. RFC 241: Deref coercions discusses why automatically borrowing arguments would make local reasoning harder. ↩ 2. RFC 1951: Expand impl Trait explains ergonomics in terms of how much you have to keep in your head, and discusses who chooses the concrete type. ↩ 3. RFC 3128: I/O safety explains the analogy between raw handles and raw pointers, and introduces owned and borrowed handle types. ↩ 4. RFC 2585: Unsafe blocks in unsafe functions separates defining safety obligations from satisfying them. The Rust 2024 edition guide covers the lint’s current default. ↩ 5. RFC 236: Error conventions recommends expressing contracts through types where possible, and using Result or Option when a stricter contract is hard to justify. The discussion of task failure predates Rust 1.0; the advice about API contracts is the relevant part here. ↩ 6. RFC 2008: Non-exhaustive enums and structs discusses exhaustive matching and the freedom to add new variants. ↩
RUST
Corrode Rust ConsultingCorrode Rust Consulting
ARTIFICIAL INTELLIGENCE

Rust Conferences 2027

Planning your Rust conference trips for 2027? Here are the events with confirmed dates so far. We’ll add more conferences, ticket prices, and call for proposals (CFP) deadlines as organizers announce them. Come say hi if you see us at any of these events! (We’ll bring Rust in Production stickers.) For this year’s events, see Rust Conferences 2026. ## Q1 2027 ### Rust Nation UK (London, UK) Rust Nation returns to London with a one-day, three-track conference at a new venue in the City of London. A separate workshop day is being planned for February 17, but is not yet confirmed. - When: February 18, 2027 - Where: 1 Basinghall Avenue, London, UK - Format: 1 day of talks across 3 tracks - Focus: Rust developers of all experience levels - Links: Website ## Q2 2027 ### TokioConf (Portland, USA) After its first edition in 2026, TokioConf returns to Portland. It’s a conference for developers working with Tokio, async Rust, and high-performance network applications. - When: April 26-27, 2027 - Where: Portland, Oregon, USA (venue to be announced) - Focus: Async Rust and Tokio - Links: Website | 2027 Announcement ### RustWeek (Utrecht, Netherlands) RustWeek brings the Rust community together in Utrecht for talks, workshops, a hackathon, and social activities. The week also includes the invitation-only Rust Project All Hands. - When: May 24-29, 2027 - Where: Utrecht, Netherlands - Format: 1 day of workshops, 2 days of talks, a hackathon, and social activities - Focus: Broad, open to Rust developers of all levels - CFP: Open — closes January 10, 2027 at 23:59 CET. Workshop proposals are handled separately via email. - Links: Website | CFP Announcement ## Q3 2027 ### RustConf (Vancouver, Canada + Online) Hosted by the Rust Foundation, RustConf heads to Vancouver in 2027, with online participation available too. More details about the program are still to come. - When: September 7-10, 2027 - Where: Vancouver, Canada, and online - Focus: Rust and its open-source ecosystem - Links: Website ## More conferences to watch We haven’t found official 2027 dates for the following conferences yet. These are events to keep an eye on, not confirmed 2027 editions: - Rustikon - Rust in Paris - Rust India - RUSTMEET - Oxidize - EuroRust - RustLab - RustForge ## Want to catch up on past events? Browse our dedicated Rust conference recordings page where you can filter by year, topic, and conference! --- Missing an event? Spot an error? Feel free to edit this list directly or let us know. Check the organizers’ websites for the latest details before booking travel. See you at the next conference! 🦀
NETHERLANDSCANADARUSTRUST FOUNDATION