Created
November 21, 2016 08:23
-
-
Save anonymous/b88f68c21491d7a6992e7bd4ec60805b to your computer and use it in GitHub Desktop.
Shared via Rust Playground
This file contains hidden or 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
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