?: operator in Rust

Is there anyway to get C style

test ? if_true : if_false

operators in Rust?

I often have these single line

let x = .. ? .. : ... ;

that becomes much more difficult to read when expanded to 5 lines.

The difference from C is that if-else is already an expression.

let x = if test { if_true } else { if_false };
10 Likes

Just a side note, the ?: operator is actually called the ternary operator.

Also, a bonus with rust is that you can have multiple conditions in an if-else statement, while you end up with odd code in C:

short foo = x < 10 ? 1 : (x < 20 ? 2 : (x < 40 ? 4 : 8));

While in rust:

let foo = if x < 10 {1} else if x < 20 {2} else if x < 40 {4} else {8};
//Or, better formatted:
let foo = if x < 10 { 1 }
     else if x < 20 { 2 }
     else if x < 40 { 4 }
               else { 8 };
2 Likes

Sorry, I forgot to mention. When using rust-fmt,

if x then {y} else {z} becomes

if x {
  y
} else {
  z
}

so it ends up taking 5 lines instead of just 1.

1 Like

I should reformulate my question as follows. Is there a way to tell rustfmt that when x,y,z fits on a single line that it should write

if x { y } else { z }

instead of

if x {
  y
} else {
  z
}

You can configure rustfmt to some extent, and I think use_small_heuristics is the setting you want. The default should already use one line for those as small as if x { y } else { z }, but you can try the "Max" setting to be more aggressive with this.

1 Like

It's less aggressive if you assign to a value. So:

let val = if test { if_true } else { if_false };

But obviously that only makes sense if you're actually going to use that value.

while you end up with odd code in C:

short foo = x < 10 ? 1 : (x < 20 ? 2 : (x < 40 ? 4 : 8));

Is that true? I recall a claim from a fairly viral blog post that virtually only PHP has such sdrawkcab-ssa associativity rules for ?:.

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.