4 ms·
I find this useful in unit tests where I often find myself duplicating blocks of assertions multiple times. The {block} helps to prevent accidentally reusing va
by bxparks 4y ago
I find this useful in unit tests where I often find myself duplicating blocks of assertions multiple times. The {block} helps to prevent accidentally reusing variables which are defined by previous blocks of assertions.
I rarely use a free-standing {block} in actual code. I think it's because if something is worthy enough to be logically grouped into a {block}, then it is probably worthwhile to pull it out into its own function, method or lambda expression.
- ithkuil 4y agoI use blocks in rust in normal code as a way to control how long a lock is held. Not sure if that's the best practice
- tialaramex 4y agoThat makes sense, you can instead specifically Drop the lock guard but the block scope ending will do that. If you aren't already it's perhaps better to identify an object that's being locked, which you can have the Mutex wrap. So e.g. you could have a Mutex<Goose>, and then functions, even methods can take a reference to a Goose to ensure you can't call them by mistake without locking the Mutex - as you otherwise don't have a Goose. If the Goose doesn't need any actual data this will be free at runtime, the compiler type check ensures you took the lock as needed but since it's a Zero Size Type no machine code is emitted to deal with a Goose variable. Probably your application has a better name for what is being protected than Goose, that's just an example, but having some object that is locked can help ensure you get the locking right and that your mental model of what is being "locked" is coherent. Of course sometimes there really is no specific thing being locked, even an imaginary one, it's just lock #4 or whatever but in my experience that's rare.