49 comments

[ 2.6 ms ] story [ 58.4 ms ] thread
I love that this is part of the syntax.

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

  ...

  return compiled;
})()'

const result = config.whatever;

// carry on

return result; ```

Really wish block were expressions in more languages.

Yes, I constantly use this pattern in C++/JavaScript, although I haven't tested how performant it is in the former (what does the compiler even do with such an expression?)
By the by, code blocks on here are denoted by two leading spaces on each line

  like
  this
Interesting that you can use blocks in JS:

  {
    const x = 5;
    x + 5
  }
  // => 10
  x
  // => undefined
But I don’t see a way to get the result out of it. As soon as you try to use it in an expression, it will treat it as an object and fail to parse.
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.

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".
Now that is pretty cool.
I want that stabilized so bad but it's not been really moving forward.
Why does this need special syntax? Couldn't blocks do this if the expression returns a result in the end?
One of the first things I tried in Rust a couple of years ago coming from Haskell. Unfortunately it's still not stabilized :(
Can this just be done as a lambda that is immediately evaluated? It's just much more verbose.

    let x = (|| -> Result<i32, std::num::ParseIntError> {
         Ok("1".parse::<i32>()?
          + "2".parse::<i32>()?
          + "3".parse::<i32>()?)
    })();
You can also de-mut-ify a variable by simply shadowing it with an immutable version of itself:

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.

Variable shadowing felt wrong for a while because it's considered verboten in so many other environments. I use it fairly liberally in rust now.
GCC adds similar syntax as an extension to C: https://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html

It's used all throughout the Linux kernel and useful for macros.

The best part of statement expressions is that a return there returns from the function itself, not from the statement expr.

I use that with with macros to return akins to std::expected, while maintaining the code in the happy-path like with exceptions.

This seems like a great way to group semantically-related statements, reduce variable leakage, and reduce the potential to silently introduce additional dependencies on variables. Seems lighter weight (especially from a cognitive load perspective) than lambdas. Appropriate for when there is a single user of the block -- avoids polluting the namespace with additional functions. Can be easily turned into a separate function once there are multiple users.
More significantly the new variables x and y in the block are Drop'd at the end of the block rather than at the end of the function. This can be significant if:

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

There are some situations with tricky lifetime issues that are almost impossible to write without this pattern. Trying to break code out into functions would force you to name all the types (not even possible for closures) or use generics (which can lead to difficulties specifying all required trait bounds), and `drop()` on its own is of no use since it doesn't effect the lexical lifetimes.
Obligatory use: it’s a block I guess

Voluntary use: I know this one. It’s a pattern now.

This is one of those natural consequences of "everything is an expression" languages that I really like! I like more explicit syntax like Zig's labelled blocks, but any of these are cool.

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.

I often employ this pattern in Ruby using `.tap` or a `begin` block.

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:

  setup_a = some_stuff
  setup_b = some_more_stuff
  i_think_this_is_setup = even_more_stuff
  the_thing = run_setup(setup_a, setup_b, i_think_this_is_setup)
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_think_this_is_setup = even_more_stuff
  
  the_thing = begin
    setup_a = some_stuff
    setup_b = some_more_stuff
    run_setup(setup_a, setup_b, i_think_this_is_setup)
  end
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.
(comment deleted)
Not mentioned in the article but kinda neat: you can label such a block and break out of it, too! The break takes an argument that becomes the value of the block that is broken out of.
This is also somewhat common in c++ with immediate-invoked lambdas
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.
I use this all the time. It's features like these that sell Rust for me honestly; even if you wrapped your whole program in `unsafe` it would still be a massively better language than C++ or C.
I think the technique is important to have in your vocabulary, but I think the examples given are a weak sell.

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.

Blocks being expressions is one of the features of the Rust language I really love (and yes I know it's not something Rust invented, but it's still not in many other popular languages).

That last example is probably my biggest use of it because I hate having variables being unnecessarily mutable.

Our codebase is full of this pattern and I love it. Every time I get clean up temporaries and expose an immutable variable outside of the setup, makes me way too happy.

A lot of the time it looks like this:

  let config = {
      let config = get_config_bytes();
      let mut config = Config::from(config);
      config.do_something_mut();
      config.do_another_mut();
      config
  };
Scala has this too, it's extremely useful
(comment deleted)