Reputation:
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?
Upvotes: 3
Views: 1080
Reputation: 181745
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.
Upvotes: 3