Skip to content

Instantly share code, notes, and snippets.

@cameronp98
Last active July 26, 2019 21:14
Show Gist options
  • Save cameronp98/a96bea1a25a44ef93f0a726700426c5b to your computer and use it in GitHub Desktop.
Save cameronp98/a96bea1a25a44ef93f0a726700426c5b to your computer and use it in GitHub Desktop.
Rust trait to parse the next item from `Iterator<Item=&str>`
trait ParseNext {
fn parse_next<T: FromStr>(&mut self) -> T;
}
impl<'a, I: Iterator<Item=&'a str>> ParseNext for I {
fn parse_next<T: FromStr>(&mut self) -> T {
self.next().unwrap().parse().unwrap()
}
}
fn main() {
let parts = "91 23 45 67 89".split_ascii_whitespace();
let a: u16 = parts.parse_next();
let b: u32 = parts.parse_next();
let c: i16 = parts.parse_next()
let d: i32 = parts.parse_next();
let e: usize = parts.parse_next();
println!("{} {} {} {} {}", a, b, c, d, e);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment