How to subtract 1 from T where T: num_traits::Num?

I'm trying to make a trait to work for all numeric integer types. I though that limiting it for num_traits::Num would force it to be applicable only to u8, u16, etc so -1 would always work.

pub fn divide_round_up<T: num_traits::Num>(value: T, divisor: T) -> T {
    return (value + divisor - 1) / divisor;
}

I get


   |
19 | pub fn divide_round_up<T: num_traits::Num>(value: T, divisor: T) -> T {
   |                        - this type parameter
20 |     return (value + divisor - 1) / divisor;
   |                               ^ expected type parameter `T`, found integer

What should I do here?

By the way, isn't there a way of doing this without the crate?

1 wouldn't be a valid thing to subtract from things like f32 (or custom structs that implement Num).

Looking at the definition of Num, however, it has One as a supertrait, which means that all things that implement Num must also implement One.

So if you import One, you should be able to do:

(value + divisor - T::one()) / divisor

By the way, isn't there a way of doing this without the crate?

Not without defining your own traits - there's nothing like this built into std currently.

1 Like

what if I wanted to add or subtract an arbitrary number?

Also, doesn't T::one adds a little extra step on runtime? Or is it all on compile time?

Presumably you have that number as a concrete type, like i32, then you need to convert that to T with TryFrom, FromPrimitive, or similar. The Num constraint only directly gives you from_str_radix.

It will almost certainly be inlined, especially for primitive types.

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.