Amani
Amani

Reputation: 18113

How can I declare a generic HashMap in a Rust struct?

The usual way to declare a HashMap in a Rust struct is as follows:

struct MyStruct {
  query: HashMap<String, String>,
  counter: u32,
}

How would I write the above code if I do not know what the HashMap would contain beforehand? I have tried the below code without success.

struct MyStruct {
  query: HashMap<K, V>,
  counter: u32,
}

Upvotes: 3

Views: 1587

Answers (1)

leun4m
leun4m

Reputation: 590

You will need to add your generics to your struct declaration as well:

struct MyStruct<K,V> {
  query: HashMap<K, V>,
  counter: u32,
}

Have a look at Rust Book/Generic Data Types

Upvotes: 6

Related Questions