Yeah, `as` is pretty much "do what C casts do except without UB" (which is basically "do what Java casts do") but/and people are justifiably uncomfortable with it. It’s very likely to go away (be deprecated) at some point as soon as someone comes up with something explicit-but-ergonomic-enough to supersede it. I’d like to see checked, overflowing, wrapping, and saturating alternatives for narrowing coercions, just like there are for arithmetic operations. Float-to-int coercions have the additional and orthogonal checked/truncating/rounding/floor/ceil axis which complicates things.
Re:A Rust match made in hell
by stonewareslord on Sunday May 01, 2022 @02:38AM
(#31222756)
You can enable a ton more lints:
#![warn(clippy::all, clippy::pedantic, clippy::nursery, clippy::cargo)]
This might be too annoying for some people, but you can choose to allow ones that don't matter and keep the rest.Notably: it will warn for as truncation, integer arithmetic (a+b can panic or overflow; use checked_/wrapping_/saturating_), calling a function in unwrap_or, etc.
Lints: https://rust-lang.github.io/rust-clippy/master/index.html
Rust's 'as' is a general cast. It will try to do something reasonable to get from one type to the other, but while a few of the casts are totally unremarkable, some others open up too much opportunity to blow your feet off in my opinion (and I am not alone). Most obviously casting from a larger to a smaller integer is silently truncating. Sometimes, often even, this is what you intended, sometimes it's unimportant, but once in a while it's a trap.
Obviously it's nothing compared to the landmines in some languages, but I think there's room to teach safer options here, warn for and eventually (in a future edition) prohibit the narrowing cast.