rust - How can I return something from HashMap.get’s None case? -
i'm wondering best practice handle none
result in getting values hashmap
. given have simple function:
pub fn get_value(&self, value: string) -> &string {
one value hashmap
unwrap
:
my_map.get(&"hello".to_string()).unwrap()
but don’t want panic if gets none
. else can do?
match self.os_config.get(&value) { some(val) => return &val, none => //?? cannot return string::new().. temporal? }
for starters, &string
type should never exist in signature; should take more general &str
. string
owned string, while &str
string slice. because string
implements deref<target = str>
, &string
coerces &str
.
when dealing hash map keys, should take &str
rather &string
, , should avoid taking string
if need &str
; don’t need consume string. can index hashmap<string, _>
&str
fine.
the type of string literal &'static str
; &'static str
quite happily coerce &'a str
'a
, can quite happily use empty string literal on none
branch. here’s result:
pub fn get_value(&self, value: &str) -> &str { match self.os_config.get(value) { some(val) => val, none => "", } }
this can written using handy unwrap_or
method:
pub fn get_value(&self, value: &str) -> &str { self.os_config.get(value).unwrap_or("") }
for reason, returning option<&str>
perhaps not tedious; other places can add .unwrap_or("")
if want to. of course, depends on desired semantics.
Comments
Post a Comment