4 ms·
In Rust, you can make your intent explicit by calling `wrapping_add` instead of using `+`.
by heinrich5991 9y ago
In Rust, you can make your intent explicit by calling `wrapping_add` instead of using `+`.
- chewbacha 9y agoAnd here’s some documentation: https://doc.rust-lang.org/std/num/struct.Wrapping.html https://doc.rust-lang.org/std/num/struct.Wrapping.html https://doc.rust-lang.org/std/primitive.u32.html#method.wrapping_add https://doc.rust-lang.org/std/primitive.u32.html#method.wrap... :)
- tspiteri 9y agoOr if this type is used a lot, you can wrap the 16-bit integer inside its own type and overload addition and/or other operators. struct Angle(i16); impl Add for Angle { type Output = Angle; fn add(self, rhs: Angle) -> Angle { Angle(self.0.wrapping_add(rhs.0)) } }
- chewbacha 9y agoThere’s already a `Wrapping<T>` struct in std for you. I don’t think you need to roll your own. Of course, it might make sense in the embedded space to do so.
- deleted 9y ago[deleted]
- jsheard 9y agoWrapping<T> actually comes from core and is just re-exported by std, so embedded targets that lack std support can still use it by importing directly from core. https://doc.rust-lang.org/core/num/struct.Wrapping.html https://doc.rust-lang.org/core/num/struct.Wrapping.html
- chewbacha 9y agoFantastic!
- Sharlin 9y ago`Wrapping<T>` is a great solution. When in doubt, encode the behavior in the type system.