Skip to content

Instantly share code, notes, and snippets.

@ubnt-intrepid
Forked from anonymous/playground.rs
Created November 21, 2016 08:24
Show Gist options
  • Save ubnt-intrepid/d386f0f810a7190be284ea3804ed5f1d to your computer and use it in GitHub Desktop.
Save ubnt-intrepid/d386f0f810a7190be284ea3804ed5f1d 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