From b94fb3b31e23f21d4d6b1075a50f880f4c3112ab Mon Sep 17 00:00:00 2001 From: Dan Buch Date: Sat, 30 Sep 2023 19:51:09 -0400 Subject: [PATCH] Remaining flow control in RBE --- rustbyexample/flow_control.d/let_else.rs | 16 ++++++++++++++++ rustbyexample/flow_control.d/while_let.rs | 13 +++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 rustbyexample/flow_control.d/let_else.rs create mode 100644 rustbyexample/flow_control.d/while_let.rs diff --git a/rustbyexample/flow_control.d/let_else.rs b/rustbyexample/flow_control.d/let_else.rs new file mode 100644 index 0000000..93dfe65 --- /dev/null +++ b/rustbyexample/flow_control.d/let_else.rs @@ -0,0 +1,16 @@ +use std::str::FromStr; + +fn get_count_item(s: &str) -> (u64, &str) { + let mut it = s.split(' '); + let (Some(count_str), Some(item)) = (it.next(), it.next()) else { + panic!("Can't segment count item pair: '{s}'"); + }; + let Ok(count) = u64::from_str(count_str) else { + panic!("Can't parse integer: '{count_str}'"); + }; + (count, item) +} + +fn main() { + assert_eq!(get_count_item("3 chairs"), (3, "chairs")); +} diff --git a/rustbyexample/flow_control.d/while_let.rs b/rustbyexample/flow_control.d/while_let.rs new file mode 100644 index 0000000..f20d680 --- /dev/null +++ b/rustbyexample/flow_control.d/while_let.rs @@ -0,0 +1,13 @@ +fn main() { + let mut optional = Some(0); + + while let Some(i) = optional { + if i > 9 { + println!("Greater than 9, quit!"); + optional = None; + } else { + println!("`i` is `{:?}`. Try again.", i); + optional = Some(i + 1); + } + } +}