Ternary Operator

Please add ternary operator support

We have a replacement for that already. if a { b } else { c } is equivalent to a ? b : c in C. Yes, you can use if in expression contexts.

3 Likes

i know, but “a ? b : c” is shorter

Пт, 9 янв. 2026 г. в 13:21, bjorn3 <notifications@rustlang.discoursemail.com>:

I'm surprised ternary isn't mentioned specifically here but nevertheless the spirit is there

6 Likes

I do wish there was a slightly more succinct way to write if a { b } else { c }, even just teaching rustfmt to be more conservative about spreading ifs in expression position across multiple lines would help.

6 Likes

There's already a setting for that, or do you mean making the default more conservative?

4 Likes

PRs welcome :slight_smile:

I agree that it both comes up often and that we're extremely unlike to add ?:, so might as well put it there.

2 Likes

If instead of the if keyword you had a suffix keyword (then), the braces would be unnecessary for disambiguation, except for the dangling else problem for nested ifs:

x < 0 then -x else x
2 Likes

si!(a, b, c). 9 characters vs 18, counting the spaces but not the expressions…but still 6 tokens, so is it really shorter?

(“si” being Spanish for “if”)

Building on select_unpredictable, maybe this would be okay naming-wise:

(x < 0).select(-x, x)

I don't think I'd ever want to have such a method where either case or both are impl Fn to be computed demand, that should stay a block.

2 Likes

And if you want a lazy-but-function-divergent path (e.g., return format!("{expensive_format}"))?

I'd hate transforming between the two if I needed that and style pressure to prefer one of the other may make code less consistent or more contorted to conform. I see the appeal for an ACP, but I don't know if it's something to recommend in any default-warn clippy lint.