In Rust you can write a foreach loop like this:
(0..arr.len()).for_each(|i| { // parens
println!("Item: {}", arr[i]);
})
or like this:
{ 0..arr.len() }.for_each(|i| { // braces
println!("Item: {}", arr[i]);
})
I know this isn't the smartest question, but which is correct? Which is the better practice?
The first, using parentheses is more idiomatic.
You're just indicating operator precedence, so that for_each
is called on the Range
created by the ..
operator, rather than on arr.len()
. This is one main function of parentheses.
The approach with curly braces creates a new block expression, which may contain multiple statements. The value of the last statement becomes the value of the block. It also gets the job done and probably compiles down to the same machine code, but is definitely a bit unusual in this case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With