Ternary operator (maybe a rehash)

⚓ Rust    📅 2025-06-23    👤 surdeus    👁️ 5      

surdeus

Warning

This post was published 49 days ago. The information described in this article may have changed.

I know that rust doesn't implement/support the C-style ternary operator:

let one_if_positive: isize = (x > 0) ? 1 : 0;

and instead uses a more general

let one_if_positive: isize = if x > 0 {
1
} else {
0
};

Rust is lovely, but this for me is a syntactic papercut. It bugs me as one of the things I like about the rust environment is rustfmt, and I like rustfmt as it fits my philosophy (ok, maybe prejudice: mostly k&r / 1tbs). This breaks that fit since it forces five lines (after rustfmt has had its way) instead of one where the philosophy.etc is "minimise vertical real-estate consumption", and the C construct allows this to be a one-liner (as above) or a three-liner:

let one_if_positive = (x > 0)
? 1
: 0;

So am I just being crabby? I know that k&r/1tbs mandate what rustfmt does, so I can't complain about that, but the ternary op allows a more compact statement where it's feasible.

Is there some deeper reason why the ternary construct would create issues with parsing (and is therefore not provided)?

I have seen on a casual goggling macro solutions, but have not investigated them. I am specifically asking why this isn't part of the 'out of the box' toolkit).

1 post - 1 participant

Read full topic

🏷️ rust_feed