Skip to content

Instantly share code, notes, and snippets.

@gary17
Created May 28, 2022 16:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gary17/d559dd634c3b63ebd4bbec95cf2e5d0c to your computer and use it in GitHub Desktop.
Save gary17/d559dd634c3b63ebd4bbec95cf2e5d0c to your computer and use it in GitHub Desktop.
Provide a default for Option<T> unwrap() through a reference to a static instance of an object, e.g. for HashMap::<&str, String>.
trait UnwrapOrEmpty<'a> {
fn unwrap_or_empty(&self) -> &'a String;
}
impl<'a> UnwrapOrEmpty<'a> for Option<&'a String> {
fn unwrap_or_empty(&self) -> &'a String {
self.unwrap_or_else(||{ // use a closure
static DEFAULT: String = String::new(); // declare a static String
&DEFAULT // return a reference to a String to match HashMap::get()
})
}
}
let map = HashMap::<String, String>::new();
let val = map.get("").unwrap_or_empty();
println!("{}", val);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment