rust - How do I sort a map by order of insertion? -
i have tried using hashmap
, btreemap
neither have worked:
use std::collections::{btreemap, hashmap}; fn main() { let mut btreemap = btreemap::new(); println!("btreemap"); btreemap.insert("z", "1"); btreemap.insert("t", "2"); btreemap.insert("r", "3"); btreemap.insert("p", "4"); btreemap.insert("k", "5"); btreemap.insert("w", "6"); btreemap.insert("g", "7"); btreemap.insert("c", "8"); btreemap.insert("a", "9"); btreemap.insert("d", "0"); (key, value) in btreemap { println!("{} {}", key, value); } println!("hash map"); let mut hashmap = hashmap::new(); hashmap.insert("z", "1"); hashmap.insert("t", "2"); hashmap.insert("r", "3"); hashmap.insert("p", "4"); hashmap.insert("k", "5"); hashmap.insert("w", "6"); hashmap.insert("g", "7"); hashmap.insert("c", "8"); hashmap.insert("a", "9"); hashmap.insert("d", "0"); (key, value) in hashmap { println!("{} {}", key, value); } }
when run via rust playground, result not sorted order of insertion; btreemap
appears ordered alphabetically (prints a c d g k p r t w z
, along numbers) , hashmap
seems ordered randomly (prints z c d r p t g wk
).
i've looked through rust standard library documentation , don't see other maps.
the default collections not track order of insertion. if wish sort that, need either find different collection does track it, or track yourself.
Comments
Post a Comment