Skip to content

Instantly share code, notes, and snippets.

Created November 21, 2016 08:23
Show Gist options
  • Save anonymous/b88f68c21491d7a6992e7bd4ec60805b to your computer and use it in GitHub Desktop.
Save anonymous/b88f68c21491d7a6992e7bd4ec60805b to your computer and use it in GitHub Desktop.
Shared via Rust Playground
trait SwapCarriable {
type Out;
fn swap_carry(self) -> Self::Out;
}
impl<T> SwapCarriable for Vec<Option<T>> {
type Out = Option<Vec<T>>;
fn swap_carry(self) -> Option<Vec<T>> {
let mut buf = Vec::with_capacity(self.len());
for e in self {
match e {
Some(e) => buf.push(e),
None => return None,
}
}
Some(buf)
}
}
impl<T, E> SwapCarriable for Vec<Result<T, E>> {
type Out = Result<Vec<T>, E>;
fn swap_carry(self) -> Result<Vec<T>, E> {
let mut buf = Vec::with_capacity(self.len());
for e in self {
buf.push(e?)
}
Ok(buf)
}
}
fn main() {
println!("{:?}", vec![Some(10), None].swap_carry());
println!("{:?}", vec![Ok(10), Ok(2)].swap_carry());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment