Hacker News new | ask | show | jobs
by remram 1222 days ago
Don't they all have == and != though?
1 comments

Sure, but in say Rust we can write for example ((v.is_empty() as i16) - 10) and Rust is OK with that, and you get either -9 if it was empty or -10 if it was not empty whereas if you didn't have that explicit cast, that's a bool not an integer, and the bool type doesn't have arithmetic so you can't subtract ten from it.
Why not use the ternary operator instead: if v.is_empty() { -9 } else { -10 }
Sure, although that's not a ternary operator, it's just an if expression.

In practice you tend to see such casts in code where we directly needed the integer. I think Clippy (Rust's linter) proposes them where you've written if some_bool { 1 } else { 0 } because well, that's what the as cast does anyway.

I find the if expression easier to read to be honest. With the integer cast example you need to mentally translate the booleans and do a subtraction in your head to figure out what integer values are involved, with the if expression it's directly visible.