←back to thread

Pitfalls of Safe Rust

(corrode.dev)
168 points pjmlp | 4 comments | | HN request time: 0.007s | source
1. conaclos ◴[] No.43605200[source]
I find it strange that the article doesn't talk about the alternative to checked arithmetic: explicit Wrapping [0] and Saturating [1] types, also provided as methods on numeric types (e.g. `usize::MAX.saturating_add(1)`).

Regarding `as` casting, I completely agree. I am trying to use safe `From::from` instead. However, this is a bit noisy: `usize::from(n)` vs `n as usize`.

[0] https://doc.rust-lang.org/std/num/struct.Wrapping.html [1] https://doc.rust-lang.org/std/num/struct.Saturating.html

replies(2): >>43605385 #>>43607272 #
2. kelnos ◴[] No.43605385[source]
> I am trying to use safe `From::from` instead. However, this is a bit noisy: `usize::from(n)` vs `n as usize`.

If there's enough information in the surrounding code for type inference to do its thing, you can shorten it to `n.into()`.

replies(1): >>43610666 #
3. mre ◴[] No.43607272[source]
True, I should add the wrapping types. They are actually quite useful if you know that you have a fixed range of values and you can't go above the min/max. Like a volume dial that just would stay at "max" if you turn up the volume; it wouldn't wrap around.
4. conaclos ◴[] No.43610666[source]
Another limitation I face is the impossibility of using `usize::from(n)` in `const` context.