4 ms·
I'm not sure if this is the best advise for rust, since you will play with variable lifetimes than.
by merb 4y ago
I'm not sure if this is the best advise for rust, since you will play with variable lifetimes than.
- kibwen 4y agoIn the context of Rust, using a block can only strictly reduce the lifetime of a local, so if that would lead to a problem it would just not compile. :P
- saghm 4y agoThis used to be standard practice in Rust before NLL (non-lexical lifetimes) were implemented. As a trivial example, here's some code that works on Rust today: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=cba65a983259ff03b6556caac0a397c6 https://play.rust-lang.org/?version=stable&mode=debug&editio... However, try to compile this with Rust 1.0 (which you can get by running `rustup update 1.0.0` and then using `cargo +1.0.0 run` or `rustc +1.0.0`) and you'll get an error saying that you can't push another element onto the vector due to it already being borrowed by the slice. This is because the borrow checker previously assumed that any borrow would remain in use for the remainder of the scope. The "fix" to this was to manually put in a block to "end" the borrow early. However, a lot of work was done to allow the borrow checker to be more sophisticated, and in Rust 1.31 (near the end of 2018: https://blog.rust-lang.org/2018/12/06/Rust-1.31-and-rust-2018.html https://blog.rust-lang.org/2018/12/06/Rust-1.31-and-rust-201...), the work allowing the compiler to recognize that a borrow was no longer used before the end of a scope and therefore would allow subsequent borrows that it previously would have considered conflicting. All that being said, there's still a useful feature of blocks in Rust that I don't see mentioned in this blog post: blocks in Rust are actually expressions! By default, the last value in a Rust block will be yielded, but you can also use the `break` keyword earlier (similar to how the return value of a Rust function will be the last value, but you can also explicitly `return` earlier). As an added bonus, this also works for `loop` blocks; since they will only ever terminate if `break` is explicitly invoked (unlike `while` or `for`), whatever value is specified will be yielded from the loop.