Generic over integers, convertable to string

Say I have a HashMap<String, String> and I want to be able to add parameters, of different types, to it. Here's a string example:

struct MyFoo {
  params: HashSet<String, String>
}

impl MyFoo {
  fn add_string<T: AsRef<str>, U: AsRef<str>>(&mut self, key: T, value: U) {
    // ...
  }
}

Now I would like to add an add_int method that is generic over any integer type. I.e. it should accept obj.add_int("foo", 3 as i16) as well as obj.add_int("bar", 5 as usize), convert the input to a string and add them to the HashMap. I saw some other - years old - posts that hint that there was an RFC which would allow this. Is there a way to accomplish this using a single generic method?

You could use the Integer trait from the num-integer crate and also Display:

fn add_int<T: AsRef<str>, U: Integer + Display>(&mut self, key: T, value: U) {
    let value = value.to_string();
}

Is there a reason you want to limit it to integers and not just all types that implement Display (or really ToString?)

1 Like

I guess not. There's already an add_param() that uses ToString. The more specific functions are there for API look'n'feel parity with an existing C++ library. We want C++ developers who want to try to use Rust for client applications to feel right at home with the interfaces.

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.