Integer bounds for generic

I'm working on a generic struct that's supposed to support all the standard integer types. As a part of the struct there's a configurable upper limit. I want to set that upper limit during construction to the integer type's maximum value.

It was suggested to me that the num crate (well, specifically the num-traits crate) could help me bound the generic type to integer types.

I have something along the lines of:

use num_traits as num;

struct Ids<T> {
  limit: T
}

impl<T: Sized + num::Bounded> Ids<T> {
  fn new() -> Result<Self, Error> {
    Ids { limit: T::max_value() }
  }

When I compile that it tells me that it expects an integer for limit, but it found "type parameter T" (in new()).

Is my assumption about that I should be able to do that wrong, or have I just not understood the syntax?

The provided code seems to work. Could you reconstruct the problematic case in playground?

1 Like

Usually you get this error when you try to influence what type T has, but T is an argument, decided by the caller, so your code can't use any concrete type in its place.

extern crate num;

fn new<T: num::Bounded>() -> T {
    1_i32
}

i32 is bounded, T must be bounded, so why i32 isn't accepted? Because the function allows any T, and it'd be incorrect if called as e.g. new::<u8>() or if someone implemented Bounded on a String and called new::<String>() (nobody will, but Rust doesn't know that).

1 Like

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.