Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rust | Which is a better practice: using curly braces vs using parentheses around expression?

Tags:

rust

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?


1 Answers

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.

like image 92
Thomas Avatar answered Sep 07 '25 19:09

Thomas