rust

Reason for a single value block in Rust


I looked at the implementation of impls::fill_bytes_via_next from the rand_core crate (0.9.3). I came upon a curious piece of code that I don't understand the reason of.

let (l, r) = { left }.split_at_mut(8);

Why is left wrapped in a block prior to calling the method? I tried leaving of the block and it works just the same, as I expected?

Does anyone know the reason for this?


Solution

  • When you use an expression as the last one in a block that forces the compiler to move that value. Here it moves left which is necessary to compile that function without non-lexical lifetimes (NLL). You can observe a compile error by compiling the function with Rust 1.35 or earlier, edition 2015.

    Since rand_core 0.9.3 uses edition 2021 and has a minimum supported Rust version of 1.63 which has NLL enabled for every edition, this is just a holdover from when it was necessary.