3 ms·
"unsafe" has a very specific meaning in the context of Rust[1][2]: particularly letting you perform actions that can potentially cause undefined behavior. Defin
by estebank 6y ago
"unsafe" has a very specific meaning in the context of Rust[1][2]: particularly letting you perform actions that can potentially cause undefined behavior. Defining `as` as saturating is removing UB. That being said, the reason it is considered unidiomatic is because saturating or wrapping might not be what your intention could be, so other ways of turning one type to another is needed and should be recommended (into and try_into). The compiler should help you in going in that direction[3], and even though rustc itself doesn't warn you away from using `as` casts, clippy can[4][5][6][7][8][9][10].
[1]: https://doc.rust-lang.org/nomicon/what-unsafe-does.html https://doc.rust-lang.org/nomicon/what-unsafe-does.html
[2]: https://nora.codes/post/what-is-rusts-unsafe/ https://nora.codes/post/what-is-rusts-unsafe/
[3]: https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=9eb6a3f199ad6c5205e64a608a752c31 https://play.rust-lang.org/?version=nightly&mode=debug&editi...
[4]: https://rust-lang.github.io/rust-clippy/master/#cast_lossless https://rust-lang.github.io/rust-clippy/master/#cast_lossles...
[5]: https://rust-lang.github.io/rust-clippy/master/#cast_possible_truncation https://rust-lang.github.io/rust-clippy/master/#cast_possibl...
[6]: https://rust-lang.github.io/rust-clippy/master/#checked_conversions https://rust-lang.github.io/rust-clippy/master/#checked_conv...
[7]: https://rust-lang.github.io/rust-clippy/master/#char_lit_as_u8 https://rust-lang.github.io/rust-clippy/master/#char_lit_as_...
[8]: https://rust-lang.github.io/rust-clippy/master/#cast_sign_loss https://rust-lang.github.io/rust-clippy/master/#cast_sign_lo...
[9]: https://rust-lang.github.io/rust-clippy/master/#cast_precision_loss https://rust-lang.github.io/rust-clippy/master/#cast_precisi...
[10]: https://rust-lang.github.io/rust-clippy/master/#cast_possible_wrap https://rust-lang.github.io/rust-clippy/master/#cast_possibl...
- saurik 6y agoIt is "removing" undefined behavior by simply defining it to be something no one would ever ever want ;P. If you are willing to just define behavior arbitrarily then I think you will find the vast majority of (but admittedly not all) undefined behaviors can be made "safe".
- ChrisSD 6y agoNobody wants undefined behaviour. That's always worse than defining it, whatever that definition is. In any case, there are better options for selecting the behaviour you want instead of using `as`.