Skip to content

Instantly share code, notes, and snippets.

View gary17's full-sized avatar

Gabriel N. gary17

View GitHub Profile
@gary17
gary17 / DowncastGenericStruct.rs
Last active May 28, 2022 18:56
Downcasting from a trait object to a generic struct that implements the trait.
trait A {
fn as_any_mut(&mut self) -> &mut dyn std::any::Any;
}
struct B<T> {
_unused: T
}
impl<T: 'static> A for B<T> { // static, else: "the parameter type `T` may not live long enough"
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
@gary17
gary17 / UnwrapOrEmpty.rs
Created May 28, 2022 16:33
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()
})
}