Live data from Hacker News

Rust's Block Pattern

notgull.net

81–90 of 121 posts

Re: Rust's Block Pattern

#82
post #68
post #24

Earlier quoted context omitted.

I want that stabilized so bad but it's not been really moving forward.

Out of curiosity why can’t a block just do this natively?

Because then you couldn't use ? to propagate errors if they occurred inside any loops or branches within the function, which would be a significant limitation.

Re: Rust's Block Pattern

#83
post #68
post #24

Earlier quoted context omitted.

I want that stabilized so bad but it's not been really moving forward.

Out of curiosity why can’t a block just do this natively?

Because it would massively alter langage semantics? It converts returns from the nearest function into returns from the nearest (try) block.

Re: Rust's Block Pattern

#84

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::sy…

I have been using this in a web application that acquires a lock, retrieves and returns a few variables to the outer scope an then immediately unlocks the mutex again

Re: Rust's Block Pattern

#86
post #48

Earlier quoted context omitted.

I just learned this one, and am gradually starting to use it! It applies for loops too. I saw it in ChatGPT code, and had to stop and look it up. Rust is a big language, for worse and for better.

I wouldn't call Rust "a big language" because of labeled break. This is a pretty standard language feature, you can do the same in C (and therefore C++), Go, Javascript, Java, C#...

Those languages don't treat blocks as expressions, so you really can't do the same thing there. Something very similar, yes. But not the same.

Re: Rust's Block Pattern

#87
post #32

This is also somewhat common in c++ with immediate-invoked lambdas

Yeah but languages that make you resort to this then don't let you simply return from the block.

And the workarounds often make the pattern be a net loss in clarity.

Re: Rust's Block Pattern

#88
post #77
post #39

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.

C++ lambdas can be used to achieve a similar result, not as pretty though https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines... But in general I agree!

The fact that you can't return from there makes for a huge difference, though,
Post reply on HN