Rust's Block Pattern

https://news.ycombinator.com/rss Hits: 17
Summary

Here’s a little idiom that I haven’t really seen discussed anywhere, that I think makes Rust code much cleaner and more robust. I don’t know if there’s an actual name for this idiom; I’m calling it the “block pattern” for lack of a better word. I find myself reaching for it frequently in code, and I think other Rust code could become cleaner if it followed this pattern. If there’s an existing name for this, please let me know! The pattern comes from blocks in Rust being valid expressions. For example, this code: …is equal to this code: …which is, in turn, equal to this code: let foo = { let x = 1; let y = 2; x + y }; So, why does this matter? Let’s say you have a function that loads a configuration file, then sends a few HTTP requests based on that config file. In order to load that config file, first you need to load the raw bytes of that file from the disk. Then you need to parse whatever the format of the configuration file is. For the sake of having a complex enough program to demonstrate the value of this pattern, let’s say it’s JSON with comments. You would need to remove the comments first using the regex crate, then parse the resulting JSON with something like serde-json. Such a function would look like this: use regex::{Regex, RegexBuilder}; use std::{fs, sync::LazyLock}; /// Format of the configuration file. #[derive(serde::Deserialize)] struct Config { /* ... */ } // Always make sure to cache your regexes! static STRIP_COMMENTS: LazyLock<Regex> = LazyLock::new(|| { RegexBuilder::new(r"//.*").multi_line(true).build().expect("regex build failed") }); /// Function to load the config and send some HTTP requests. fn foo(cfg_file: &str) -> anyhow::Result<()> { // Load the raw bytes of the file. let config_data = fs::read(cfg_file)?; // Convert to a string to the regex can work on it. let config_string = String::from_utf8(&config_data)?; // Strip out all comments. let stripped_data = STRIP_COMMENTS.replace(&config_string, ""); // Parse as JSON. let config = serd...

First seen: 2025-12-19 21:18

Last seen: 2025-12-20 13:28