rustHow to use a tuple as a key in a Rust HashMap?
Tuples can be used as keys in a Rust HashMap by implementing the Hash and Eq traits. This can be done by using the #[derive(Hash, Eq)] annotation on the tuple struct.
#[derive(Hash, Eq)]
struct TupleStruct(i32, i32);
use std::collections::HashMap;
let mut map = HashMap::new();
let key = TupleStruct(1, 2);
map.insert(key, "value");
The example code above creates a tuple struct TupleStruct with two i32 fields, and implements the Hash and Eq traits on it. Then, a HashMap is created and a key is created from the TupleStruct. Finally, the key is used to insert a value into the HashMap.
#[derive(Hash, Eq)]: Annotation to implement theHashandEqtraits on a tuple struct.TupleStruct(i32, i32): Tuple struct with twoi32fields.HashMap::new(): Creates a newHashMap.let key = TupleStruct(1, 2): Creates a key from theTupleStruct.map.insert(key, "value"): Inserts a value into theHashMapusing the key.
Helpful links
Related
- How to sort a Rust HashMap?
- How to print a Rust HashMap?
- How to create a HashMap of pointers in Rust?
- How to build a Rust HashMap from an iterator?
- How to pop an element from a Rust HashMap?
- How to create a HashMap of structs in Rust?
- How to create a nested HashMap in Rust?
- How to create a HashMap of HashMaps in Rust?
- How to create a new Rust HashMap with values?
- How to lock a Rust HashMap?
More of Rust
- How to use regex lookbehind in Rust?
- How to perform matrix operations in Rust?
- Regex example to match multiline string in Rust?
- How to replace all using regex in Rust?
- How to use regex lookahead in Rust?
- How to pop an element from a Rust HashMap?
- How to split a string by regex in Rust?
- How to use regex to match a double quote in Rust?
- Generator example in Rust
See more codes...