That makes a lot of sense. I'm going to convert my code to do this.
When narrowing an integer, would as
be idiomatic, try_into
, or either?
That makes a lot of sense. I'm going to convert my code to do this.
When narrowing an integer, would as
be idiomatic, try_into
, or either?
It depends on the desired behavior. try_into will error and return nothing useful, while as will truncate. As far as I'm aware, there's not yet a suitable replacement for truncating (though I may just be unaware of it).
try_into
is better.
For two reasons: it is more limited in what kind of casts it does, and it will catch overflow.
In order to be as explicit as possible, I tried using into/try_into in place of as
for all integer conversions, but in the end I went back to as
. It turned out that the behavior I wanted, and had been aware of when originally coding, is exactly what I get from as
, and the result is more readable.