How would I idiomatically create a string to string hashmap in rust. The following works, but is it the right way to do it? is there a different kind of string I should be using?
use std::collections::hashmap::HashMap; //use std::str; fn main() { let mut mymap = HashMap::new(); mymap.insert("foo".to_string(), "bar".to_string()); println!("{0}", mymap["foo".to_string()]); }
String is as a key of the HashMap When you create a HashMap object and try to store a key-value pair in it, while storing, a hash code of the given key is calculated and its value is placed at the position represented by the resultant hash code of the key.
In summary, use String if you need owned string data (like passing strings to other threads, or building them at runtime), and use &str if you only need a view of a string.
As we discuss above String is immutable, its hashcode is cached at the time of creation and it doesn�t need to be calculated again. This makes it a great candidate for key in a Map and it�s processing is fast than other HashMap key objects. This is why String is mostly used Object as HashMap keys.
Assuming you would like the flexibility of String
, HashMap<String, String>
is correct. The other choice is &str
, but that imposes significant restrictions on how the HashMap
can be used/where it can be passed around; but if it it works, changing one or both parameter to &str
will be more efficient. This choice should be dictated by what sort of ownership semantics you need, and how dynamic the strings are, see this answer and the strings guide for more.
BTW, searching a HashMap<String, ...>
with a String
can be expensive: if you don't already have one, it requires allocating a new String
. We have a work around in the form of find_equiv
, which allows you to pass a string literal (and, more generally, 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 I've left the Option
in the return value, one could call .unwrap()
or handle a missing key properly).
Another slightly different option (more general in some circumstances, less in others), is the std::string::as_string
function, which allows viewing the data in &str
as if it were a &String
, without allocating (as the name suggests). It returns an object that can be dereferenced to a String
, e.g.
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
.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With