Rust’s Block Pattern
notgull.net·2d·
🦀Rust
Preview
Report Post

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, t…

Similar Posts

Loading similar posts...