Alternative to the ternary operator in Rust
June 13, 2022 ‐ 1 min read
In contrast to many C-like languages Rust doesn't support the ternary ?:
syntax. For the time being at least. Instead, if-else statements can be used as expressions, which does make ternary operations in Rust fairly easy to read.
Since if-else statements can be used as an expression in Rust we can directly use them in return statements and assignment operations.
See for example an if-else expression directly in a return
statements.
return if x > 1 { success } else { failure };
Or you may use an if-else expression in an assignment operations.
let result = if x > 1 { true } else { false };