←back to thread

Pitfalls of Safe Rust

(corrode.dev)
168 points pjmlp | 3 comments | | HN request time: 0.202s | source
Show context
woah ◴[] No.43603395[source]
Is "as" an uneccesary footgun?
replies(4): >>43603560 #>>43603887 #>>43603998 #>>43605135 #
bombela ◴[] No.43603998[source]
Compared to C/C++ "as" feels so much safe r. Now that Rust and we the programmers have evolved with it, I too feel that "as" for narrowing conversion is a small foot gun.
replies(1): >>43605165 #
1. bigstrat2003 ◴[] No.43605165[source]
I'm struggling to see how you would implement narrowing conversion in a way that is harder for programmers to misuse when they aren't being mindful, while also being pleasant to use when you really do want to just drop higher bits. Like, you could conceivably have something like a "try_narrow" trait which wraps the truncated value inside an Err when it doesn't fit, and it would probably be harder to accidentally misuse, but that's also really cumbersome to use when you are trying to truncate things.
replies(2): >>43605460 #>>43606023 #
2. woah ◴[] No.43605460[source]
let foo: u8 = bar<u64>.truncate_to()?
3. recursivecaveat ◴[] No.43606023[source]
I don't really want narrowing conversion to be harder, I just want checked conversion to be at least nearly as convenient. `x as usize` vs `x.try_into().unwrap()` becomes `x tiu usize` or something even. I'm not picky. It's kindof funny that this is the exact mistake C++ made, where the safe version of every container operation is the verbose one: `vector[]` vs `vector.at()` or `*optional` vs `optional.value()`, which results in tons and tons of memory problems for code that has absolutely no performance need for unchecked operations.