Rust fold HashMap to a single string
If you are here for the first time, I don’t usually write this kind of post, but it was pretty hard to find a simple code to fold a HasMap in rust.
In this use case, I had a hash map with server names and a boolean indicating if the server ack the message or not.
use std::collections::HashMap;
fn main() {
// inits hash_map
let mut hash = HashMap::new();
// Add itens to the hash map
hash.insert(String::from("servers:1"), true);
hash.insert(String::from("servers:2"), true);
hash.insert(String::from("servers:3"), false);
// Fold the hashmap
let string_result = hash.into_iter().fold(
String::from(""), /*Initial value*/
|accumulator: String, value: (String, bool) /* each value*/| {
String::from(format!(
"{}, {}:{}",
accumulator.to_owned(),
value.0.to_owned(),// Access props with number fields
value.1.to_owned()
))
},
);
println!("{}", string_result);
}
Conclusion
I hope it can help you if you get here via searching on the internet, see you in the next one.
Written on June 18, 2022