rust create hashmap from delimited data in string
To create a hashmap from delimited data in a string in Rust, you can use the split
method to split the string into key-value pairs, and then use the collect
method to collect them into a hashmap. Here's an example:
use std::collections::HashMap;
fn main() {
let data = "key1:value1,key2:value2,key3:value3";
let hashmap: HashMap<_, _> = data
.split(',')
.map(|pair| {
let mut iter = pair.split(':');
(iter.next().unwrap(), iter.next().unwrap())
})
.collect();
println!("{:?}", hashmap);
}
This code splits the input string data
into individual pairs using the comma delimiter. Each pair is then split further using the colon delimiter, and the resulting key-value pairs are collected into a hashmap. Finally, the hashmap is printed for verification.