While trying to solve a LeetCode problem with Rust, I encountered a strange issue: it looks like I can't create a HashMap
with primitive types:
use std::collections::HashMap;
fn two_sum(nums: &Vec<i32>, target: i32) -> (usize, usize) {
let mut map = HashMap::new();
for (i, x) in nums.iter().enumerate() {
match map.get(target - x) {
Some(k) => return (k, i),
None => map.insert(x, i)
};
}
return (0, 0);
}
fn main() {
let ret = two_sum(&vec![1,2,3], 4);
println!("{}, {}", ret.0, ret.1);
}
The compiler complains:
error[E0308]: mismatched types
--> two_sum.rs:6:23
|
6 | match map.get(target - x) {
| ^^^^^^^^^^ expected reference, found i32
|
= note: expected type `&_`
= note: found type `i32`
error[E0308]: mismatched types
--> two_sum.rs:7:32
|
7 | Some(k) => return (k, i),
| ^ expected usize, found reference
|
= note: expected type `usize`
= note: found type `&_`
Is it necessary to always use reference with HashMap in Rust?
EDIT:
Looks like it is necessary... The solution looks a bit ugly but works anyway.
use std::collections::HashMap;
fn two_sum(nums: &[i32], target: i32) -> (usize, usize) {
let mut map = HashMap::new();
for (i, x) in nums.iter().enumerate() {
let df = target - x;
if map.contains_key(&df) {
return (*map.get(&df).unwrap(), i);
}
map.insert(x, i);
}
return (0, 0);
}
fn main() {
let ret = two_sum(&vec![1,2,3], 4);
println!("{}, {}", ret.0, ret.1);
}
I wonder if there is a better solution or some best practice to use HashMaps with primitive types?
two_sum
to take a&[i32]
argument (as it is allows for a strict superset of possible arguments).