Skip to content

Instantly share code, notes, and snippets.

@jeremychone
Last active August 29, 2024 12:56
Show Gist options
  • Save jeremychone/0ab136d13f773249f309208ad1e330bb to your computer and use it in GitHub Desktop.
Save jeremychone/0ab136d13f773249f309208ad1e330bb to your computer and use it in GitHub Desktop.
Rust 1.65 - let-else statements - new language feature!!! For youtube video: https://www.youtube.com/watch?v=U-5_bumwH9w&list=PL7r-PXl6ZPcCIOFaL7nVHXZvBmHNhrh_Q)
//! For youtube video: https://www.youtube.com/watch?v=U-5_bumwH9w&list=PL7r-PXl6ZPcCIOFaL7nVHXZvBmHNhrh_Q
/// Guard pattern with let-else
/// e.g., "my_key: 123"
pub fn key_num_guard_1(item: &str) -> Result<(&str, i32), &'static str> {
let Some((key, val)) = item.split_once(':') else {
return Err("Invalid item");
};
let Ok(val) = val.trim().parse::<i32>() else {
return Err("Invalid item");
};
Ok((key, val))
}
/// Guard pattern with two guards, ok_or, and map_err
pub fn key_num_guard_2(item: &str) -> Result<(&str, i32), &'static str> {
let (key, val) = item.split_once(':').ok_or("Item wrong format")?;
let val = val
.trim()
.parse::<i32>()
.map_err(|_| "Item value not i32")?;
Ok((key, val))
}
/// Guard pattern with one final guard (ok_or)
pub fn key_num_guard_3(item: &str) -> Result<(&str, i32), &'static str> {
let (key, val) = item
.split_once(':')
.and_then(|(key, val)| val.parse().ok().map(|val| (key, val)))
.ok_or("Invalid item")?;
Ok((key, val))
}
/// Nested if/else
/// e.g., "my_key: 123"
pub fn key_num_1(item: &str) -> Result<(&str, i32), &'static str> {
if let Some((key, val)) = item.split_once(':') {
if let Ok(val) = val.trim().parse::<i32>() {
Ok((key, val))
} else {
Err("Invalid item")
}
} else {
Err("Invalid item")
}
}
/// Return early on Ok
/// e.g., "my_key: 123"
pub fn key_num_2(item: &str) -> Result<(&str, i32), &'static str> {
if let Some((key, val)) = item.split_once(':') {
if let Ok(val) = val.trim().parse::<i32>() {
return Ok((key, val));
}
}
Err("Invalid item")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment