简体   繁体   中英

How to generalize a HashMap passed to a function with different types of keys?

I have a hm1: HashMap<K, V> where K is a tuple (k1, 2, k3) and V is a tuple of 10 elements like (v1, v2, v3, /* ... */ v10) .

I have a function which acts on that HashMap , so I pass it as a parameter:

fn do_something(hm1: HashMap<(&i64, &i64, &Option<i64>), (&i64, &i64, /* ... */ &i64)>) -> () {
    //Access k1, k2, k3 and v1 .. v10 and do something with it
}

I have a second HashMap hm2 where the only difference is an additional key element. hm2: HashMap<K, V> where K is a tuple (k1, k2, k3, k4) and V is again a tuple of 10 elements (v1, v2, v3, /* ... */ v10) .

I would want to avoid copy pasting the same do_something() function with an adapted signature, because the logic inside is nearly the same. The difference is just that I have an additional k4 element in the tuple which I'd also access then if I have hm2 .

Is there a way to generalize the HashMap<K, V> parameter so I could pass both HashMap s and act on them without duplicating my function?

I would want to avoid copy pasting the same do_something() function with an adapted signature, because the logic inside is nearly the same.

Copying nearly identical code for different types is what Rust generics are designed for! If the values are the same type in both cases, and only the keys are different, you can abstract over the keys:

type Value<'a> = (&'a i64, &'a i64, /* ... */ &'a i64);

fn do_something<K>(hash_map: HashMap<K, Value<'_>>) {
    for value in hash_map.values() {
        // do something with the value
    }
}

Given that you know nothing about the keys inside the function, you can't do much with them. In particular, you can't destructure them to access individual elements of the key tuples.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM