Does Rust have a similar shorthand as javascript.
let value = condition1 == true ? 0 : 1;
Is there something similar to this?
Does Rust have a similar shorthand as javascript.
let value = condition1 == true ? 0 : 1;
Is there something similar to this?
let value = if condition { 0 } else { 1 };
Thanks, still a bit more verbose than I was hoping for but works, so ty
In the special case where you only want 0
or 1
, you can cast a bool
value as an integer.
let value = !condition as i32;
I wouldn't actually use it in real code, but I thought this was a cute place to use extension traits:
let value = (2 + 2 == 4).if_true(42).otherwise(0);
If you're going that path, using Option
as an intermediary would seem reasonable.
let value = (2 + 2 == 4).then(|| 42).unwrap_or(0);
Personally I'd just use the standard if/else, but there are obviously options.
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.