Tristan F.-R.
Tristan F.-R.

Reputation: 4204

Get amount of elements in a HashMap

I would like to know how to get the amount of elements in a HashMap with rust.

I'm currently using this to check if a HashMap is empty or not, so if there is a more idiomatic way to get that as well, I would love to know both.

Upvotes: 1

Views: 1448

Answers (1)

pigeonhands
pigeonhands

Reputation: 3414

std::HashMap has a len method to check for the number of elements, but you can use is_empty method to check if it contains any items.

let mut map = HashMap::new();
assert!(map.is_empty());
assert_eq!(map.len(), 0);

a.insert(1, "a");
assert!(!map.is_empty());
assert_eq!(map.len(), 1);

Upvotes: 8

Related Questions