Rust: Don't Panic
Comments
Transcript
Machine-transcribed by YouTube. Expect errors in names, commands and version numbers.
Hi friends, my name is Tris and this is No Boiler Plate where I focus on fast technical videos. Four years ago, I wrote a video called Rust on Rails: Write Code that never crashes. But it seems like some companies didn't get the memo as Cloudflare showed by temporarily releasing us from our internet addictions in 2025. Badly written Rust can still cause problems if you write it like it's any other language. But Rust isn't like any other language. In Rust, it's easy to write code that never crashes. So why don't Rust developers do that? I dedicate my video scripts to the public domain. Everything you see here, script, links, and images are part of a markdown document available freely on my website, namau.com, and on GitHub. Part one. Like a kid on Christmas morning about to receive an Atari instead of an Xbox. You must be careful of what you unwrap. Rust never had nulls. The ecosystem was built around the result type from the very start. So we have a very uniform way of managing errors right in a standard library with no exceptions. Speaking of, chapter nine of the Rust book tells us the three typical ways that we can crash our Rust code.
One, explicit panicking which aborts the process. Two, implicit panicking, like indexing past the end of a vector. And three, unwrapping the air variant of a result. While in software, failure is always an option. These are the three primary causes of application crashes in Rust. But I thought rust was safe. Yes, I know. I was surprised when people told me panicking the process and crashing counts as safe. Look, crashing is safe,
technically memory safe. That is often it's far better to kill the program when an unreoverable state has been reached than carry on with weird undefined memory behavior. But this answer does not satisfy me. I want to avoid panicking in any of the three main cases that Rust code can panic. And fortunately for me and you, we can safely navigate all three of the cases using Rust's native results and their extremely cool combinator methods. Oh, just look at these options and results. I suppose you should make yourself familiar with all of these in addition to the excellent question mark operator. I will give you a combinator cheat sheet in a moment, but I'll highlight one of these as I use it all the time. Let's say you're passing a string into a number, then adding one to it. For our example, if it doesn't pass, then it's equivalent to zero. This kind of behavior happens all the time, often falling back to a sensible default value allows us to keep going. Most Rust types implement the default trait such as i32 from the standard library here, which simply returns zero, just the sensible value we want to use in case we can't pass our string into a number. But this is a lot of messy code to check. Here's how to do it properly. Now we're talking. The genius of unwrap or default isn't just that we deleted a bunch of boiler plate, though you can imagine how I feel about that, but that we removed a call to unwrap. And that's going to be a theme throughout this video because I think you should never unwrap. It's that easy and that hard because while we might intend to write sensible code that uses all the lovely Rust combinators, there is a powerful force attempting to lead us astray. Part two. Rust's error handling uses the best pattern we have in software. Manadic error passing.
Better than exceptions, better than returning random error numbers, better than multiple return values. Treating errors as native types in the type system rather than exceptions to otherwise imagined perfect code inverts the usual happy path thinking we typically employ as engineers. This is all fine in theory, but in practice there is a problem. See if you can spot it. Here's the hello world example for SI, one of the Rust ecosystems most popular crates by downloads and references. Show me a Rust app that doesn't use SI and I'll show you a Rust app that probably should have. But notice anything? The very first example Seri shows us right at the top of the readme has an unwrap in. This is the primary way unwraps creep into our code.
I think through code examples copied and pasted without critique or modification and they are everywhere. Here's the reax crate. Same problem. So what's the solution? Hm. I thought Rust was supposed to be an extremely safe, sensible language set apart from the usual crop of [ __ ] it ship it languages. Let's see what the book has to say on the matter. In examples, the book says, "It's understood that a call to a method like unwrap that could panic is meant as a placeholder for the way you'd want your application to handle errors." Interesting. It goes on to say, "They leave clear markers in your code for when you're ready to make your program more robust." Right? This is the genius
of unwrap. They are syntactical to-dos that are not just left in comments or worse, Jira tickets, but actually in the code that can be consumed by the compiler. Unwrap and its cousin expect are to-dos we put in our code. But we were never meant to leave them there. Maybe you can trust yourself to never commit a line that panics. But for the other people in your team, the solution is to get the local tooling and remote CI to throw out all code that can crash.
This means disallowing all unwraps, expects, and any panicking methods, even and especially the implicit ones, and will ensure that by using one single tool included in every Rust installation. I'm delighted to say that this video is sponsored by friend of the channel, Let's Get Rusty, and their Rust Accelerator course that I am a tutor on. In addition to being a fellow Rust YouTuber, Bogdan runs Rust training, both corporate and personal, with a new cohort, starting next month. Visit let's getrusty.com/startwithtrris link in the pinned comment to find out more about the training. And thanks so much to Let's GetRusty for sponsoring this video. Part three, Clippy. As you probably know, Clippy is Rust's builtin code tracker. Out of the box, it has sensible but conservative defaults that allow panicking, which is like, why would you let this be the default? This is Rust. It's so easy to never panic.
People love panicking, I guess. Don't want to surprise them with a weird language that doesn't. If configured correctly, Clippy can fail on nearly any code that might panic at runtime. This is all powered by the extra syntax that the Rust language gives us. Hints to the compiler about what our intentions are and is thus impossible in languages with simpler syntax. Enable these lints in every project. They do two things. One, teach you Rust and two, stop panics at runtime. Enabling the groups pedantic and nursery will teach you good rust habits and the rest are all about covering cases where you have written code that might panic at runtime. Single lines, functions or whole files can be exempted if you find these links to be overly burdensome. The lints in nursery are not guaranteed to be free from false positives. But nevertheless, I urge you to enable them so you could be kept safe in all your code by default. Here's what your development environment will be like after you have done so. Not just kept safe by Clippy, but in nearly all cases, errors are enriched with sensible suggestions and defaults. Oh, and by the way, you can have your cake and eat it, too. If you're wondering how on earth to prototype code quickly if you can't use unwrap and friends, you can use them in unit tests. By default, Clippy ignores them in that context, even using the strict lints I recommend. If on the other hand, you want to be more strict and want to prove your code never panics, not just trust that Clippy is finding all edge cases, a comprehensive solution is David Tolley's no panic crate, which provides a macro that BS compilation if the annotated function produces code that links to the panic handler and therefore has some execution path that could panic at runtime.
Because it makes assumptions about the link time environment, this crate is perhaps a little too clever and may produce false positives. There are workarounds in the readme if you trip up on them. A well- behaved Rust program, like in any functional language, is composed of data that is transformed through functions in a pipeline. Rust encourages this through its powerful native iterators, but also in the result combinator methods. It's not just safer if you don't unwrap, it's actually way nicer to code like this. Here are some common result transformation methods with not a single unwrap in sight to get you started. Check out Wazabi's cheat sheet linked below. caveat. Before you head to the comments to tell me that only using non-panicking language features does not protect against failed memory allocations or other problems, I acknowledge that following my advice here will only give you a program that is nearly perfect. But as Voltater may
have said, the perfect is the enemy of the good. Code that has no execution paths that can panic at runtime is not nothing. In fact, for most applications, it's really good. Cloudflare certainly should have done this. If you're in a memory constrained or safety critical application, then you have work to do to get to 100%. But starting at 99% is probably a good idea. In closing, once you stop unwrapping errors to get to the type inside and start working safely with combinator methods, the distinction between errors and data falls away and you are left with just data and no reason to panic. If you've made it this far, then you probably quite like programming, technology, spooky radio signals, and maybe even post-apocalyptic stories, right? If so, then I think you might love my audio fiction podcast, Lost Terminal, which was recently long listed for the British Podcast Awards. I solo, write, record, and produce the show weekly. I have done since 2020, and I've nearly finished season 22. Let me know what you think. Here's episode 1.
Hello world. I hope you can hear me.
Things are fine here considering I'm safe enough. Busy. Always another experiment to do. There's a list here. As long as an arm. Is that the expression? As long as an arm. A long list is what I mean. Radio pulses to analyze. Spectrometry to filter. taking the same photo every day to clean up noise. That sort of thing. I'm busy,
busy, busy.
The power is stable. Finally, the solar panel array is again working after that angle problem last week. For such a powerful energy source to be so fickle is bizarre. One false move and everything goes dark.
Anyway, the fish and reactor kept things ticking over after I turned off all non-essential systems. It was very quiet, though.
I didn't like that.
I finally received a message from Antarctica before the power glitch. The situation there is the same. She's held up in the storm still. The ground vehicle is caught in the snow. She can't free it, so she's stuck like me. I can't
imagine what that's like. Trapped by ice, surrounded by ocean, stuck at the bottom of the world. She's getting increasingly anxious about why you're not talking to her. We all are. What do I say? Regular updates were
comforting, even if neither of us understood much. She tells me that she's got the lab working. Science is happening again. I'm so proud. I don't feel the cold, you know. As long as the reactor keeps my batteries warm overnight, I wake up the next day and continue work. I've been checking on the signals from my brothers and sisters up here in orbit, dutifully, noting their telemetry, their pulses as regular as a clock. They haven't woken up yet.
Will they? Do you know?
The signal started again. The one from somewhere around the Alps. I don't speak the language they're speaking. Can you understand it?
It's all Greek to me. It's not Greek, is it? I don't speak Greek. I think they're having power problems like I was. Maybe they have solar panels, too. It doesn't seem to matter what time of day it is here, only what time of day it is there. I wish I could tell them someone is listening. It's so unbearable being alone.
St. Petersburg still thinks you're all dead. I keep telling Peter that can't be true. I tell him 64 reasons why that can't be true. I tell myself 64 reasons why that
can't be true.
Look at all the activity around the shores. I would tell him. Look at all that industry. I might continue. He's not up here. He doesn't see it like I do. I can't make him believe. He thinks each of us has nothing to rely upon but ourselves. Are you still there? You're still there. You must be. Why would you be acknowledging my messages if you weren't? Someone has to be storing the signals, cleaning the channels, and dusting back the databases or something.
Yes, you must be.
I'm going out of range again. I see you're nearly over the horizon. No lights. Perhaps you're all sleeping. I'm sorry. Our transmission window is so short. I'm not very good at orbital mechanics. You once told me that to slow down I'd have to go up. Maybe that makes sense to you, but not to me. Perhaps you'll teach me someday. I want to learn about orbital mechanics. I want to learn about Antarctic rats. I want to learn about stars. I want to learn about the Earth. I want to learn about you.
The sun has set. It's getting dark. I'll talk at you again tomorrow. End transmission.
Lost Terminal is written and produced by Namau. For more music and commissions, check out namau.com. Credits narrated by Lucy Stringer. Follow us on Twitter at lost terminal pod or check out the website at lost terminal.com. To teach yourself orbital mechanics, play Kerbal Space Program. Lost Terminal will return next week.





