Mesclar dois HashMaps em Rust
Então, eu estou um pouco preso, tentando mesclar dois HashMaps.
É fácil fazer isso em linha:
fn inline() {
let mut first_context = HashMap::new();
first_context.insert("Hello", "World");
let mut second_context = HashMap::new();
second_context.insert("Hey", "There");
let mut new_context = HashMap::new();
for (key, value) in first_context.iter() {
new_context.insert(*key, *value);
}
for (key, value) in second_context.iter() {
new_context.insert(*key, *value);
}
println!("Inline:\t\t{}", new_context);
println!("Inline:\t\t{}\t{} [Initial Maps Still Usable]", first_context, second_context);
}
É fácil o suficiente fazer uma função:
fn abstracted() {
fn merge<'a>(first_context: &HashMap<&'a str, &'a str>, second_context: &HashMap<&'a str, &'a str>) -> HashMap<&'a str, &'a str> {
let mut new_context = HashMap::new();
for (key, value) in first_context.iter() {
new_context.insert(*key, *value);
}
for (key, value) in second_context.iter() {
new_context.insert(*key, *value);
}
new_context
}
let mut first_context = HashMap::new();
first_context.insert("Hello", "World");
let mut second_context = HashMap::new();
second_context.insert("Hey", "There");
println!("Abstracted:\t{}", merge(&first_context, &second_context));
println!("Abstracted:\t{}\t{} [Initial Maps Still Usable]", first_context, second_context);
}
No entanto, não consigo obter a versão genérica para funcionar:
fn generic() {
fn merge<'a, K: Hash + Eq, V>(first_context: &HashMap<&'a K, &'a V>, second_context: &HashMap<&'a K, &'a V>) -> HashMap<&'a K, &'a V> {
let mut new_context = HashMap::new();
for (key, value) in first_context.iter() {
new_context.insert(*key, *value);
}
for (key, value) in second_context.iter() {
new_context.insert(*key, *value);
}
new_context
}
let mut first_context = HashMap::new();
first_context.insert("Hello", "World");
let mut second_context = HashMap::new();
second_context.insert("Hey", "There");
println!("Generic:\t{}", merge(&first_context, &second_context));
println!("Generic:\t{}\t{} [Initial Maps Still Usable]", first_context, second_context);
}
O código acima em play.rust-lang.org.
Compilando:
error: the trait `core::kinds::Sized` is not implemented for the type `str`
Eu entendo que o compilador está confuso sobre o tamanho do valor genérico, mas não sei por que "str" não tem um tamanho estrito de memória? Eu sei que é uma fatia de String e não um tipo, mas ainda assim deve funcionar, não? Isso é um inseto?
Eu pensei que isso seria uma função relativamente trivial. Se alguém tiver uma boa solução, eu adoraria aprender. Na verdade, idealmente, eu adoraria ver uma solução com umtrait Mergeable
e escreva um decorador para o HashMap <& K, & V>, para que eu possa chamarlet new_context = first_context.merge(&second_context);
mas isso pode ser uma pergunta diferente.