Created
August 30, 2024 17:40
-
-
Save jac18281828/59a9dfb014a680bc4497ac01c72fc1f7 to your computer and use it in GitHub Desktop.
Parse values of different types in rust, pipelined
This file contains 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
use anyhow::Result; | |
enum Numbers { | |
One, | |
Two, | |
Three, | |
} | |
enum Names { | |
John, | |
Jane, | |
Doe, | |
} | |
fn main() -> Result<()> { | |
let n = vec!["One", "Two", "Three", "John", "Jane", "Doe", "Stink"]; | |
n.into_iter() | |
.filter_map(|x| { | |
parse_numbers(x) | |
.map(|n| { | |
number_handler(n); | |
() | |
}) | |
.or_else(|| { | |
parse_names(x).map(|n| { | |
name_handler(n); | |
() | |
}) | |
}) | |
.or_else(|| { | |
default_handler(); | |
Some(()) | |
}) | |
}) | |
.for_each(drop); | |
Ok(()) | |
} | |
fn parse_numbers(n: &str) -> Option<Numbers> { | |
match n { | |
"One" => Some(Numbers::One), | |
"Two" => Some(Numbers::Two), | |
"Three" => Some(Numbers::Three), | |
_ => None, | |
} | |
} | |
fn parse_names(n: &str) -> Option<Names> { | |
match n { | |
"John" => Some(Names::John), | |
"Jane" => Some(Names::Jane), | |
"Doe" => Some(Names::Doe), | |
_ => None, | |
} | |
} | |
fn number_handler(n: Numbers) { | |
match n { | |
Numbers::One => println!("One"), | |
Numbers::Two => println!("Two"), | |
Numbers::Three => println!("Three"), | |
} | |
} | |
fn name_handler(n: Names) { | |
match n { | |
Names::John => println!("John"), | |
Names::Jane => println!("Jane"), | |
Names::Doe => println!("Doe"), | |
} | |
} | |
fn default_handler() { | |
println!("No match found"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment