|
|
|
|
|
by voorwerpjes
1248 days ago
|
|
I like how this highlights the pitfalls of using `as` to cast between types. The article says to prefer using `try_into()` instead of `as`, which is a good suggestion when available, but `as` lets you cast between floats and ints, while `try_into` is not implemented for these type conversions. I think the reasoning is it is unclear `try_into` should fail when it had to round a decimal number down or only when the float was something above the bounds or `NaN`. Regardless it seems like a missed opportunity in the standard library. https://play.rust-lang.org/?version=stable&mode=debug&editio... |
|
The article also says "If you upcast u32 to u64, you can use the keyword as". I would avoid this. In these cases you can just use `.into()`. This is infallible and will raise errors if refactoring causes that conversion to no longer be infallible. (In which case you can fix it or migrate to `.try_into()`)
I think the floating point case is similar. Keep `as` super suspicious, but sometimes you do want to do it.