Skip to content

Instantly share code, notes, and snippets.

@outfrost
Created February 3, 2024 01:25
Show Gist options
  • Save outfrost/08617a78002ece59b6a15f3024a01767 to your computer and use it in GitHub Desktop.
Save outfrost/08617a78002ece59b6a15f3024a01767 to your computer and use it in GitHub Desktop.
Rust "extension method" to turn empty containers into Nones
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