How can I port C++ code that uses the ternary operator to Rust?

Viewed 8936

How can I port this C++ code to Rust:

auto sgnR = (R >= 0.) ? 1. : -1.;

I have seen some examples with the match keyword, but I don't understand how it works.

2 Answers

As of Rust 1.50, you can use bool::then to accomplish the same thing:

let sgn_r = (r >= 0).then(|| 1).unwrap_or(-1);

Note that it is generally better to use a regular if/else statement for readability reasons, but bool::then is an alternative that may be nicer in certain circumstances.

Related