Tech News
← Back to articles

Rust's Block Pattern

read original related products more articles

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:

let foo = { 1 + 2 };

…is equal to this code:

let foo = 1 + 2 ;

…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 .

... continue reading