Hacker News new | past | comments | ask | show | jobs | submit login

Or 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))
        }
    }



There’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.


Wrapping<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


Fantastic!


`Wrapping<T>` is a great solution. When in doubt, encode the behavior in the type system.




Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact

Search: