Rust's Block Pattern
Key topics
Rust's block pattern is sparking lively discussions, with many commenters sharing their experiences using similar constructs in other languages like C++, JavaScript, and Kotlin. While some are thrilled about the syntax, others are exploring the performance implications, with one commenter noting that compilers often inline closures, eliminating overhead. The conversation is also branching out to related topics, such as JavaScript's experimental "do expressions" proposal and Kotlin's scope functions, highlighting the diverse ways languages tackle similar problems. As commenters compare and contrast these approaches, a broader understanding of the trade-offs and design choices is emerging.
Snapshot generated from the HN discussion
Discussion Activity
Very active discussionFirst comment
9h
Peak period
67
Day 1
Avg / period
16.9
Based on 118 loaded comments
Key moments
- 01Story posted
Dec 18, 2025 at 11:56 PM EST
19 days ago
Step 01 - 02First comment
Dec 19, 2025 at 8:30 AM EST
9h after posting
Step 02 - 03Peak activity
67 comments in Day 1
Hottest window of the conversation
Step 03 - 04Latest activity
Dec 31, 2025 at 10:41 AM EST
6d ago
Step 04
Generating AI Summary...
Analyzing up to 500 comments to identify key contributors and discussion patterns
Want the full context?
Jump to the original sources
Read the primary article or dive into the live Hacker News thread when you're ready.
I typically use closures to do this in other languages, but the syntax is always so cumbersome. You get the "dog balls" that Douglas Crockford always called them:
``` const config = (() => { const raw_data = ...
})()'const result = config.whatever;
// carry on
return result; ```
Really wish block were expressions in more languages.
(Not to be confused with do notation)
https://kotlinlang.org/docs/scope-functions.html
Actually, Kotlin's with() and apply() are more powerful than what Rust can provide. Then again, Rust isn't designed with OO in mind, so you probably shouldn't use those patterns in Rust anyway.
also: https://github.com/JetBrains/kotlin/blob/2.3.0/libraries/std...
apply: https://github.com/JetBrains/kotlin/blob/2.3.0/libraries/std...
let: https://github.com/JetBrains/kotlin/blob/2.3.0/libraries/std...
with: https://github.com/JetBrains/kotlin/blob/2.3.0/libraries/std...
run (two overloads): https://github.com/JetBrains/kotlin/blob/2.3.0/libraries/std... and https://github.com/JetBrains/kotlin/blob/2.3.0/libraries/std...
These all heavily rely on Kotlin's ability to write an extension function for any class. When you write `with(x) { something() }` you're extending the type of `x` (be that int, List<String>, or SomeObject) with an anonymous method, and passing that as a second parameter.
Consider the signature here:
The first object is a generic object T, which can be anything. The second is a member function of T that returns R, which again can be just about anything, as long as it operates on T and returns R.Let does it kind of diferently:
This is an extension method that applies to every single class as T isn't restricted, so as long as this function is in scope (it's in the standard library so it will be), every single object will have a let() method. The only parameter, block, is a lambda that takes T and returns R.So for instance:
is syntactic sugar for something like: You could absolutely write any of these yourself. For instance, consider this quick example I threw together: https://pl.kotl.in/S-pHgvxlXThe type inference is doing a lot of heavy lifting, i.e. taking a lambda and automatically turning it into an anonymous extension function, but it's nothing that you cannot do yourself. In fact, a wide range of libraries write what might look like macros in Kotlin by leveraging this and the fact you can define your own inline operators (i.e. https://pl.kotl.in/TZB0zA1Jr).
The second example "erasure of mutability" makes more sense. But this effectively makes it a Rust-specific pattern.
https://doc.rust-lang.org/beta/unstable-book/language-featur...
https://www.tomshardware.com/software/linux/linux-dev-swatte...
Murderous and wretched Rust proponents will censor, downplay and distract from this.
You only live once.
https://github.com/rust-lang/rust/pull/148725
https://github.com/rust-lang/rust/pull/149489
The closest thing I can think of that will let you return a result from within a separate scope using a set of foo()? calls would be a lambda function that's called immediately, but that has its own problems when it comes to moving and it probably doesn't compile to very fast code either.
This works fine: https://play.rust-lang.org/?version=stable&mode=debug&editio...
let mut data = foo(); data.mutate(); let data = data;
May be preferable for short snippets where adding braces, the yielded expression, and indentation is more noise than it's worth.
For example I feel this is right:
It's used all throughout the Linux kernel and useful for macros.
I use that with with macros to return akins to std::expected, while maintaining the code in the happy-path like with exceptions.
- Drop does something, like close a file or release a lock, or
- x and y don't have Send and/or Sync, and you have an await point in the function or are doing multi-threaded stuff
This is why you should almost always use std::sync::Mutex rather than tokio::sync::Mutex. std's Mutex isn't Sync/Send, so the compiler will complain if you hold it across an await. Usually you don't want mutex's held across an await.
https://doc.rust-lang.org/beta/unstable-book/language-featur...
AFAIU it essentially creates a variable in inner scope but defers drop to the outer scope so that you can return the reference
Also in Kotlin, Scala, and nim.
Try this out, you can actually (technically) assign a variable to `continue` like:
let x = continue;
Funnily enough, one of the few things that are definitely always a statement are `let` statements! Except, you also have `let` expressions, which are technically different, so I guess that's not really a difference at all.
It barely adds any functionality but it's useful for readability because of the same reasons in the OP.
It helps because I've been bitten by code that did this:
That's all fine until later on, probably in some obscure loop, `i_think_this_is_setup` is used without you noticing.Instead doing something like this tells the reader that it will be used again:
I now don't mentally have to keep track of what `setup_a` or `setup_b` are anymore and, since the writer made a conscious effort not to put it in the block, you will take an extra look for it in the outer scope.let input = read_input(); let trimmed_input = input.trim(); let trimmed_uppercase_input = trimmed_input.uppercase();
...
The extra variable names are almost completely boilerplate and make it also annoying to reorder things.
In Clojure you can do
(-> (read-input) string/trim string/upcase)
And I find that so much more readable and refactorable.
Very often if you think harder you realise you didn't want this, you should write say, a function (from which you can return) or actually you didn't want to break early at all. Not always, but often. If you write more "break 'label value" than just break then you are almost certainly Doing It Wrong™.
Hopefully try blocks will allow using ? inside of expression blocks in the future, though.
And the workarounds often make the pattern be a net loss in clarity.
It is available as a language extension in Clang and GCC and widely used (e.g. by the Linux kernel).
Unfortunately it is not supported by the third major compiler out there so many projects can't or don't want to use it.
In the example given, I would have preferred to extract to a method—-what if I want to load the config from somewhere else? And perhaps the specific of strip comments itself could have been extracted to a more-semantically-aptly named post-processing method.
I see the argument that when extracted to a function, that you don’t need to go hunting for it. But if we look at the example with the block, I still see a bunch of detail about how to load the config, and then several lines using it. What’s more important in that context—-the specifics of the loading of config, or the specifics of how requests are formed using the loaded config?
The fact that you need to explain what’s happening with comments is a smell. Properly named variables and methods would obviate the need for the comments and would introduce semantic meaning thru names.
I think blocks are useful when you are referencing a lot of local variables and also have fairly localized meaning within the method. For example, you can write a block to capture a bunch of values for logging context—-then you can call that block in every log line to get a logging context based on current method state. It totally beats extracting a logging context method that consumes many variables and is unlikely to be reused outside of the calling method, and yet you get delayed evaluation and single point of definition for it.
So yes to the pattern, but needs a better example.
There are DRY and WET principles. We can argue which one of them is better, but to move something used exactly once to a method just due to an anxiety you can need it again seems to me a little bit too much. I move things into functions that are called once, but iff it makes my code clearer. It can happen when code is already complicated and long.
The block allows you to localize the code, and refactoring it into a separate function will be trivial. You need not to check if all the variables are temporary, you just see the block, copy/paste it, add a function header, and then add function call at the place where the block was before. No thinking and no research is needed. Veni, vidi, vici.
> The fact that you need to explain what’s happening with comments is a smell.
It is an example for the article taken out of a context. You'd better comment it for the sake of your readers.
> I think blocks are useful when you are referencing a lot of local variables and also have fairly localized meaning within the method.
I do it each time I need a temporary variable. I hate variables that exist but are not used, they make it harder to read the code, you need to track temporaries through all the code to confirm that they are temporaries. So even if I have just two local variables (not "a lot of") and one of them is temporary, I'd probably localize the temporary one even further into its own block. What really matters is a code readability: if the function has just three lines, it doesn't matter, but it becomes really ugly if a lifetime of a variable overshoots its usefulness for 20 lines of a dense code.
The other thing is mutability/immutability: you can drop mutability when returning a value from a block. Mutability makes reasoning harder, so dropping it when you don't need it anymore is a noble deed. It can and will reduce the complexity of reading the code. You'll thank yourself many times later, when faced with necessity to reread your own code.
There is a code and there is the process of devising the code. You cannot understand the former without reverse engineering the latter. So, when you write code, the more of your intentions are encoded somehow in your code, the easier it will be to read your code. If you create temporary variables just to parse config with the final goal to get the parsed config in a variable, then you'd better encode it. You can add comments, like "we need to parse config and for that we need three temporary variables", or you can localize those three temporary variables in a block.
That last example is probably my biggest use of it because I hate having variables being unnecessarily mutable.
I think the author misunderstood something....
Voluntary use: I know this one. It’s a pattern now.
Good to see Rust supports this technique as well.
0 - https://docs.oracle.com/javase/tutorial/java/javaOO/initial....
A lot of the time it looks like this:
Much of the value of this block pattern is that it makes the scope of the intermediate variables clear, so that you have no doubt that you don’t need to keep them in mind outside that scope.
But it’s also about logical grouping of concepts. And that you can achieve with simple ad hoc indentation:
(Aside: that code is dreadful. None of the inner-level comments are useful, and should be deleted (one of them is even misleading). .multi_line(true) does nothing here (it only changes the meanings of ^ and $; see also .dot_matches_new_line(true)). There is no binding config_string (it was named data_string). String::from_utf8 doesn’t take a reference. fs::read_to_string should have been used instead of fs::read + String::from_utf8. Regex::replace_all was presumably intended.)It might seem odd if you’re not used to it, but I’ve been finding it useful for grouping, especially in languages that aren’t expression-oriented. Tooling may be able to make it foldable, too.
I’ve been making a lightweight markup language for the last few years, and its structure (meaning things like heading levels, lists, &c.) has over time become almost entirely indentation-based. I find it really nice. (AsciiDoc is violently flat. reStructuredText is mostly indented but not with headings. Markdown is mostly flat with painfully bad and footgunny rules around indentation.)
—⁂—
A related issue. You frequently end up with multiple levels of indentation where you really only want one. A simple case I wrote yesterday in Svelte and was bothered by:
In some ancient code styles it might have been written like this instead: Not the prettiest due to the extra mandatory curlies, but it’s fine, and the structure reasonable. In Rust it’s nicer: But rustfmt would insist on returning it to this disappointment: Perhaps the biggest reason around normalising indentation and brace practice was bugs like the “goto fail” one. I think there’s a different path: make the curly braces mandatory (like Rust does), and have tooling check that matching braces are at the same level of indentation. Then the problem can’t occur. Once that’s taken care of, I really see no reason not to write things more compactly, when you decide it is nicer, which I find quite frequently compared with things like rustfmt.I would like to see people experiment with indentation a bit more.
—⁂—
One related concept from Microsoft: regions. Cleanest in C♯, `#region …` / `#endregion` pragmas which can introduce code folding or outlining or whatever in IDEs.
In any case, the real solution here is to simply allow proper nested functions that behave exactly like freestanding functions in that they can only access what's passed to them:
This way you can actually reason about that block of code in isolationSame effect as when calling a freestanding function, except this doesn't expose the nested function to callers outside the parent function, which is valuable.