Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Ref https://old.reddit.com/r/programming/comments/1l2h781/on_no_syntactic_support_for_error_handling/mvy5zrd/
- use regex::Regex;
- fn main() {
- println!("{}", foo("123"));
- println!("{}", bar("123").unwrap_or(0));
- println!("{}", baz("123").unwrap_or(0));
- }
- fn foo(input: &str) -> isize {
- let p = Regex::new(r"-c(\d{1,3})")
- .expect("We should have written a valid regex. This is a bug in the application.");
- p.captures(input)
- .and_then(|captures| captures.get(1))
- .and_then(|m| m.as_str().parse().ok())
- .unwrap_or(0)
- }
- fn bar(input: &str) -> Option<isize> {
- let p = Regex::new(r"-c(\d{1,3})").ok()?;
- let captures = p.captures(input)?;
- let matches = captures.get(1)?;
- matches.as_str().parse().ok()
- }
- fn baz(input: &str) -> Option<isize> {
- Regex::new(r"-c(\d{1,3})")
- .ok()?
- .captures(input)?
- .get(1)?
- .as_str()
- .parse()
- .ok()
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement