Created
February 3, 2024 01:25
-
-
Save outfrost/08617a78002ece59b6a15f3024a01767 to your computer and use it in GitHub Desktop.
Rust "extension method" to turn empty containers into Nones
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
fn main() { | |
let a = String::from("This is a test").drop_empty(); | |
println!("{:?}", &a); | |
let b = String::from("").drop_empty(); | |
println!("{:?}", &b); | |
let c = vec![0, 69, 420].drop_empty(); | |
println!("{:?}", &c); | |
} | |
trait DropEmpty: Sized { | |
fn drop_empty(self) -> Option<Self>; | |
} | |
impl DropEmpty for String { | |
fn drop_empty(self) -> Option<String> { | |
if self.is_empty() { | |
None | |
} else { | |
Some(self) | |
} | |
} | |
} | |
impl<T> DropEmpty for Vec<T> { | |
fn drop_empty(self) -> Option<Vec<T>> { | |
if self.is_empty() { | |
None | |
} else { | |
Some(self) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment