3 ms·
The article quickly mentions implementing addition: ``` impl Add for NonZeroF32 { ... } impl Add<f32> for NonZeroF32 { ... } impl Add<NonZeroF32> for f32 {
by fph 8mo ago
The article quickly mentions implementing addition:
```
impl Add for NonZeroF32 { ... }
impl Add<f32> for NonZeroF32 { ... }
impl Add<NonZeroF32> for f32 { ... }
```
What type would it return though?
- alfons_foobar 8mo agoWould have to be F32, no? I cannot think of any way to enforce "non-zero-ness" of the result without making it return an optional Result<NonZeroF32>, and at that point we are basically back to square one...
- MaulingMonkey 8mo ago> Would have to be F32, no? Generally yes. `NonZeroU32::saturating_add(self, other: u32)` is able to return `NonZeroU32` though! ( https://doc.rust-lang.org/std/num/type.NonZeroU32.html#method.saturating_add https://doc.rust-lang.org/std/num/type.NonZeroU32.html#metho... ) > I cannot think of any way to enforce "non-zero-ness" of the result without making it return an optional Result<NonZeroF32>, and at that point we are basically back to square one... `NonZeroU32::checked_add(self, other: u32)` basically does this, although I'll note it returns an `Option` instead of a `Result` ( https://doc.rust-lang.org/std/num/type.NonZeroU32.html#method.checked_add https://doc.rust-lang.org/std/num/type.NonZeroU32.html#metho... ), leaving you to `.map_err(...)` or otherwise handle the edge case to your heart's content. Niche, but occasionally what you want.
- alfons_foobar 8mo ago> `NonZeroU32::saturating_add(self, other: u32)` is able to return `NonZeroU32` though! I was confused at first how that could work, but then I realized that of course, with _unsigned_ integers this works fine because you cannot add a negative number...
- fph 8mo agoYou'd still have to check for overflow, I imagine. And there are other gotchas, for instance it seems natural to assume that NonZeroF32 * NonZeroF32 can return a NonZeroF32, but 1e-25 * 1e-25 = 0 because of underflow.
- WJW 8mo agoI imagine it would be something like Option<NonZeroF32>, since -2.0 + 2.0 would violate the constraints at runtime. This gets us the Option handling problem back. I think the article would have been better with NonZeroPositiveF32 as the example type, since then addition would be safe.