Hello,
In the following code why the second for
need {}
? The second for
just has one command.
fn main() {
let mut x = [[0;10];4];
for i in 0..4 {
for j in 0..10 {
x[i][j]=0;
}
}
}
Thank you.
Hello,
In the following code why the second for
need {}
? The second for
just has one command.
fn main() {
let mut x = [[0;10];4];
for i in 0..4 {
for j in 0..10 {
x[i][j]=0;
}
}
}
Thank you.
Yes. In C, the {}
are optional, but the ()
around the loop condition are mandatory. However, Rust has made the opposite choice where {}
is required and ()
is optional.
It's not really possible to make both optional. It makes parsing the language ambiguous.
Yes. Rust has decided its syntax works this way.
All questions of the form "Why does Rust does not copy feature X from language Y" have similar answers.
I let others argue here about the reasoning for this particular design decision.
By the way, there are excellent reasons to make {}
mandatory. From the Linux kernel coding style:
Don’t put multiple statements on a single line unless you have something to hide:
if (condition) do_this; do_something_everytime;
When the {}
is mandatory, you cannot do this kind of thing.
I for one am very happy that Rust does require those {}
around single statements. I'm all in favour of consistency. The "principle of least surprises" as they say. Those surprises have often annoyed me in C.
Note that the match
statement allows single expressions without braces:
fn main() {
match 2 {
1 => {
println!("One");
}
2 => println!("Two"), // no braces, but comma required at end
3 => {
println!("Three");
}
_ => {
println!("Many or none or negative");
}
}
}
Hmm.. still, match
is consistent with if
, for
, in that it requires {}
even if there is only one match arm:
enum X {
A(u32),
}
let y = match t {
X::A(z) => z,
};
As useless as that may be...
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.