HashMap Key with derive(Hash)
Write a Rust function that defines a Point struct deriving Hash and Eq, inserts it as a key in a HashMap with an associated value, and retrieves the value. The Hash trait enables instances to be hashed for use in hash-based data structures like HashMap and HashSet.
Using custom types as HashMap keys requires both Hash and Eq (which implies PartialEq). The Hash trait computes a hash value from the struct's fields, while Eq ensures keys can be compared for exact equality during lookup. Deriving both is straightforward: #[derive(Hash, Eq, PartialEq)]. The derived hash combines field hashes using a well-defined algorithm.
HashMap is Rust's default hash table implementation. Using custom structs as keys is common for lookup tables, caching, and memoization. The derive macros ensure that the hash and equality implementations are consistent: equal structs always produce equal hashes, which is a fundamental requirement for correct HashMap behavior.
Time complexity is O(1) average for insertion and lookup. Space complexity is O(n) for the map. The HashMap uses the SipHash algorithm by default, which provides protection against HashDoS attacks.
Edge cases include hash collisions (HashMap handles them internally), structs with floating-point fields (NaN != NaN breaks Eq requirements), and ensuring the struct fields implement both Hash and Eq for the derive to work.
Example Input & Output
Point(5,6) maps to 30
Point(3,4) maps to 20
Point(1,2) maps to value 10
Override previous value
Same point different value
Algorithm Flow

Solution Approach
Best Answers
use std::collections::HashMap;
#[derive(Hash, Eq, PartialEq)]
struct Point {
x: i32,
y: i32,
}
fn solution(x: i32, y: i32, val: i32) -> i32 {
let mut map = HashMap::new();
let p = Point { x, y };
map.insert(p, val);
map[&Point { x, y }]
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
