can I use a tuple as a key in a HashMap in rust?
- User
can I use a tuple as a key in a HashMap in rust?
- Assistant
Yes, you can use a tuple as a key in a
HashMapin Rust, given that each element of the tuple implements theEqandHashtraits. This is because theHashMapuses these traits to determine how to equate keys (withEq) and how to hash them (withHash).Here's an example on how you might do this:
use std::collections::HashMap; fn main() { // Declaring a HashMap where the key is a tuple of (i32, i32) let mut map: HashMap<(i32, i32), String> = HashMap::new(); // Inserting values into the map map.insert((1, 2), "Value at (1, 2)".to_string()); map.insert((3, 4), "Value at (3, 4)".to_string()); // Accessing values if let Some(value) = map.get(&(1, 2)) { println!("Found: {}", value); } else { println!("No value found for key (1, 2)"); } }