Assignment of integers using num-trait

I'd like to impose an "integers only" trait bound. A while back someone told me about the num crate, and it's really nifty -- but I'm having some trouble wrapping my head around this one:

Playground

I've been trying to add other trait bounds, but I'm starting to realize I'm going about it the wrong way.

There’s different kinds of integers. You could be referring to just the primitive integer types i.e. something like u8, u16, etc. and i8, i16, etc.. You could also be referring to more general cases of integers, including arbitrarily sized ones like e.g. from the num-bigint crate. Well — okay — that one wouldn’t be Bounded, but maybe you want to start counting at zero anyways?

To make your code compile as-is, you would require something like AddAssign<T> + One + Bounded + Copy. If you don’t feel too bad about requiring a bit more but typing less, you could also resort to NumAssign + Bounded + Copy.

If you want to support something like bigint (the linked example here as well as the following ones counts from zero), you could weaken Copy to Clone.

If you want to add something different from 1, you can use from_str_radix or require extra From<u8> or TryFrom<u8> or FromPrimitive bounds.

If you only want to use primitive integer types anyways and like simple trait bounds, maybe just use PrimInt and rewrite the +=.

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.