Created
May 28, 2022 16:33
-
-
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>.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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