Assuming you need String flexibility, HashMap<String, String> true. Another option is &str , but this imposes significant restrictions on how the HashMap / can be used / where it can be passed; but if it works, changing one or both parameters to &str will be more efficient. This choice should be dictated by the necessary semantics of ownership and row dynamics, see this answer and the manual line for more.
By the way, finding a HashMap<String, ...> with String can be expensive: if you don't already have one, it needs to allocate a new String . We have work in the form of find_equiv , which allows us to pass a string literal (and, in a more general sense, any &str ) without allocating a new String :
use std::collections::HashMap; fn main() { let mut mymap = HashMap::new(); mymap.insert("foo".to_string(), "bar".to_string()); println!("{}", mymap.find_equiv(&"foo")); println!("{}", mymap.find_equiv(&"not there")); }
playpen (note that I left Option in the return value, you could call .unwrap() or handle the missing key properly).
Another slightly different option (more general in some cases, less in others) is the std::string::as_string , which allows you to view data in &str as if it were &String , without highlighting (as the name suggests ). It returns an object that can be dereferenced by String , for example.
use std::collections::HashMap; use std::string; fn main() { let mut mymap = HashMap::new(); mymap.insert("foo".to_string(), "bar".to_string()); println!("{}", mymap[*string::as_string("foo")]); }
playpen
(There is a similar std::vec::as_vec .)
huon
source share