Skip to content

Instantly share code, notes, and snippets.

@cometkim
Last active May 6, 2025 00:17
Show Gist options
  • Save cometkim/4c89194a1ce61f668c6363d0e6a507c2 to your computer and use it in GitHub Desktop.
Save cometkim/4c89194a1ce61f668c6363d0e6a507c2 to your computer and use it in GitHub Desktop.
Illustrate how early-returning syntax (let-else) in Rust eliminates nested pattern matching

Maybe you can flat using dot-free style function calls too.

However, it unnecessarly add runtime overhead, pollute the callstack, and even not intuitive as direct-style control flows are.

lazy_static! {
static ref RE: Regex = Regex::new(r"^(?P<alg>[A-Za-z0-9_+.-]+):(?P<hash>[A-Fa-f0-9]+)$").unwrap();
}
fn from_str_v1(s: &str) -> Result<Self, Self::Err> {
RE.captures(s)
.and_then(|cap| match (cap.name("alg"), cap.name("hash")) {
(Some(alg), Some(hash)) => match SupportedAlgorithm::from_str(alg.as_str()) {
Ok(alg) => Some(Self {
alg,
hash: hash.as_str().to_string(),
}),
_ => None,
},
_ => None,
})
.ok_or_else(|| RegistryError::DigestInvalid)
}
fn from_str_v2(s: &str) -> Result<Self, Self::Err> {
let Ok(cap) = RE.captures(s) else {
return Err(RegistryError::DigestInvalid)
}
let (Some(alg), Some(hash)) = (cap.name("alg"), cap.name("hash")) else {
return Err(RegistryError::DigestInvalid)
}
let Ok(alg) = SupportedAlgorithm::from_str(alg.as_str()) else {
return Err(RegistryError::DigestInvalid)
}
Ok(Self {
alg,
hash: hash.as_str().to_string(),
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment