Top
Best
New

Posted by zdw 5 days ago

Rust's Block Pattern(notgull.net)
217 points | 114 commentspage 3
pkulak 4 days ago||
I got so used to taking advantage of this feature in my side projects that my work Kotlin code is now full of “run {}” blocks. Even with a GCed language, it’s very nice to restrict variable lifetimes without needing to split the logic out to its own function.
domlebo70 4 days ago||
We do this via run in TS:

    export const run = <T>(f: () => T): T => {
      return f();
    };
notpushkin 4 days ago|
Can you clarify why do you prefer this over an IIFE `(() => {...})()`?
deredede 4 days ago||
I like it. IIFEs always make me nervous because they look like they beg to be removed if you don't know why they are used. Using an explicit function such as `run` looks much more intentional, and provide a single intuitive place (the documentation of the `run` function) to explain the pattern.
lenkite 5 days ago||
The first example given is not at all convincing. Its is clear as the sky that loading the config file should be be a separate function of its own. Coupling sending HTTP requests with it makes no sense.

The second example "erasure of mutability" makes more sense. But this effectively makes it a Rust-specific pattern.

dtdynasty 5 days ago|
It's essentially an inline function with only 1 client. Can be a preference for inline readability and automatically enforces there are no other clients of the "function".
ngruhn 5 days ago||
Reminds of Brian Wills OOP rant video from 2016. He advocates exactly for this pattern: https://www.youtube.com/watch?v=QM1iUe6IofM&t=2235s
sonu27 4 days ago||
When would you use the block pattern vs creating a new function?
HackerThemAll 4 days ago||
This is a great addition to the best patterns and practices in Rust. Worth noting and using. In JavaScript there's the proposal of "do expressions" which accomplish the same.
j16sdiz 4 days ago||
> This is why I generally avoid C’s “bottom-up” strategy for organizing code.

I think the author misunderstood something....

charlie-83 4 days ago|
Yeah, language choice and the way your organise your code seem orthogonal to me
dap 3 days ago||
I inferred that they’re referring to the fact that in typical C the compiler must have seen a function earlier in the file for you to use it. One solution (that the author doesn’t like) is to put the leaf functions first so that they’re defined when the compiler sees their callers. The author seems to be ignoring the alternative approach: declaring functions at the top and then writing the in the top-down order that they like.
rienbdj 4 days ago|
This is Rusts OCaml roots showing :)
More comments...