rust
48 lines · 8 steps
Converting HTTP codes with TryFrom in Rust
A fallible conversion turns raw u16 status codes into a typed enum, with a custom error for anything unrecognized.
Explained by
highlit
1use std::convert::TryFrom;
2
3#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4pub enum HttpStatus {
5 Ok,
6 Created,
7 NoContent,
8 BadRequest,
9 Unauthorized,
10 Forbidden,
11 NotFound,
12 InternalServerError,
13}
14
15#[derive(Debug, PartialEq, Eq)]
16pub struct InvalidStatus(u16);
17
18impl std::fmt::Display for InvalidStatus {
19 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
20 write!(f, "{} is not a supported HTTP status code", self.0)
21 }
22}
23
24impl std::error::Error for InvalidStatus {}
25
26impl TryFrom<u16> for HttpStatus {
27 type Error = InvalidStatus;
28
29 fn try_from(value: u16) -> Result<Self, Self::Error> {
30 match value {
31 200 => Ok(HttpStatus::Ok),
32 201 => Ok(HttpStatus::Created),
33 204 => Ok(HttpStatus::NoContent),
34 400 => Ok(HttpStatus::BadRequest),
35 401 => Ok(HttpStatus::Unauthorized),
36 403 => Ok(HttpStatus::Forbidden),
37 404 => Ok(HttpStatus::NotFound),
38 500 => Ok(HttpStatus::InternalServerError),
39 other => Err(InvalidStatus(other)),
40 }
41 }
42}
43
44impl HttpStatus {
45 pub fn is_success(self) -> bool {
46 matches!(self, HttpStatus::Ok | HttpStatus::Created | HttpStatus::NoContent)
47 }
48}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1TryFrom models conversions that can fail, returning a Result instead of panicking or silently defaulting.
- 2A dedicated error type that implements Display and Error integrates cleanly with the wider Rust error ecosystem.
- 3Modeling a closed set of values as an enum lets the compiler enforce exhaustiveness and enables ergonomic helper methods.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
rust
use std::cmp::{Ordering, Reverse}; use std::collections::BinaryHeap; use std::fs::File; use std::io::{self, BufRead, BufReader, BufWriter, Lines, Write};
K-way merge of sorted logs in Rust
binary-heap
k-way-merge
streaming-io
Intermediate
8 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
rust
use std::f64::consts::PI; #[derive(Debug, Clone, Copy)] pub struct LatLng {
Building geographic bounding boxes in Rust
geospatial
value-types
option
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/converting-http-codes-with-tryfrom-in-rust-explained-rust-41f9/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.