Rust: Beware Parentheses on If Conditionals

Assuming that the three conditions represent Booleans, I noticed that code based on this rust would compile, where this would be a syntax error in C#. In rust, the if statement does not require grouping conditions within parentheses. Without noting parentheses placement carefully, I believe that, at least for developers familiar with languages where if requires parentheses to group one or more conditions. At the very least, using parentheses unnecessarily, incorrectly, unknowingly, or otherwise makes their intention unclear and could result in accidental incorrect grouping of conditions leading to defects.

This compiles.

if(condition1
    || condition2)
    || condition3
{
    // do something
}

In rust, if statements do not require parentheses. Normally, the compiler generates a warning, as in the following case.

fn main() {
    if (1 == 2) {
        println!("That is impossible!");
    }
}

The compiler does not generate a warning in the following case where the parentheses are not required. The outermost parentheses of the if statement are interpreted as grouping select conditions rather than as a container for grouping all conditions.

fn main() {
    if (1 == 2) || 1 == 1 {
      println!("That is possible!");
    }
}

I do not have an immediate example and I do not suggest that this is a defect in the language, but I believe that there are cases where this could allow certain types of errors in conditions that could be hard to spot, and that developers new to rust should be aware of this concern.

Screen shots from before I moved curly braces to make my rust look less like C#.

One thought on “Rust: Beware Parentheses on If Conditionals

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: