Generics in Rust

Can I have something like:

fn get_count(cont: HashMap<_,_>)->HashMap::size_type//return value is pseudo code

What is HashMap::size_type?

Are you having a specific implementation in mind for this function? Sizes of collections in Rust are usually usize. If you want to know the size of a hashmap, you can use HashMap::len; if you use this method in a gen_count function it would look like

fn get_count<Key, Value>(cont: &HashMap<Key, Value>) -> usize {

Hi and thanks for the reply.
No, this fn is only an example. I rather ask if in general such constructs are available in Rust.

Are you referring to associated types?

trait Sized {
  type Size;
  fn size(&self) -> Self::Size;

fn get_size<S: Sized>(collection: &S) -> S::Size {

Note that unlike C++, you need to use a trait here. Rust does typechecking on a generic function where it is written, not when the generic type is substituted.

1 Like

Hi, I guess this would be the equivalent.
Thank you

1 Like

For the record, since there already is a trait called “Sized” in the prelude (wich does something completely different), the name “Sized” for defining a new trait in Rust is not the best choice.


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.