我正在寻找Java的HashMap初始化的Rust等效。
Java:
Map<String, List<String>> map = new HashMap<String, List<String>>();
map.put("1", Arrays.asList("one"));
map.put("2", Arrays.asList("two", "three"));
map.put("3", Arrays.asList("four", "five", "six"));
如果您希望您的字符串是String
类型,含义,运行时字符串:
use std::collections::HashMap;
fn main() {
let mut map: HashMap<String, Vec<String>> = HashMap::new();
map.insert("1".to_string(), vec!["one".to_string()]);
map.insert("2".to_string(), vec!["two".to_string(), "three".to_string()]);
map.insert("3".to_string(), vec!["four".to_string(), "five".to_string(), "six".to_string()]);
println!("{:?}", map);
}
{"1": ["one"], "3": ["four", "five", "six"], "2": ["two", "three"]}
否则,如果字符串都是静态的并且在编译时已知:
use std::collections::HashMap;
fn main() {
let mut map: HashMap<&str, Vec<&str>> = HashMap::new();
map.insert("1", vec!["one"]);
map.insert("2", vec!["two", "three"]);
map.insert("3", vec!["four", "five", "six"]);
println!("{:?}", map);
}
第三,如果您的数组在编译时也是已知的:
use std::collections::HashMap;
fn main() {
let mut map: HashMap<&str, &[&str]> = HashMap::new();
map.insert("1", &["one"]);
map.insert("2", &["two", "three"]);
map.insert("3", &["four", "five", "six"]);
println!("{:?}", map);
}
要了解更多信息,请阅读'static
关键字(在我们的&
类型中隐式使用),slices
和the difference between &str and String
。
改进虽然示例的目的是尽可能接近Java代码,但您也可以使用HashMap::from
:
use std::collections::HashMap;
fn main() {
let map = HashMap::from([
("1", vec!["one"]),
("2", vec!["two", "three"]),
("3", vec!["four", "five", "six"]),
]);
println!("{:?}", map);
}