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 theHash
andEq
traits on a tuple struct.TupleStruct(i32, i32)
: Tuple struct with twoi32
fields.HashMap::new()
: Creates a newHashMap
.let key = TupleStruct(1, 2)
: Creates a key from theTupleStruct
.map.insert(key, "value")
: Inserts a value into theHashMap
using the key.
Helpful links
Related
- How to convert a Rust HashMap to JSON?
- How to remove an element from a Rust HashMap if a condition is met?
- How to convert a Rust HashMap to a BTreeMap?
- How to implement PartialEq for a Rust HashMap?
- How to create a HashMap of HashMaps in Rust?
- How to use a Rust HashMap in a multithreaded environment?
- How to convert a Rust HashMap to a JSON string?
- How to compare two Rust HashMaps?
- How to clear a Rust HashMap?
- How to pop an element from a Rust HashMap?
More of Rust
- How to match whitespace with a regex in Rust?
- How to replace a capture group using Rust regex?
- How to use regex to match a double quote in Rust?
- How to calculate the inverse of a matrix in Rust?
- How to match the end of a line in a Rust regex?
- How to use non-capturing groups in Rust regex?
- How to use regex with bytes in Rust?
- How to create a HashSet from a Vec in Rust?
- How to convert a Rust HashMap to JSON?
See more codes...