Fix a let Some(…) = …; binding that fails with a refutable-pattern error
value_of should return the part of a config line after the first =, and an empty string when the line has no =. It does not compile: error[E0005]: refutable pattern in local binding.
Constraints:
- Keep the signature
fn value_of(line: &str) -> &str. - No
unwrap,expector panic: a line without=returns"". mainprints"8080" "".
fn value_of(line: &str) -> &str {
let Some((_, value)) = line.split_once('=');
value
}
fn main() {
println!("{:?} {:?}", value_of("port=8080"), value_of("verbose"));
}Find and fix the bug.
Some((_, value)) is refutable: it fails when split_once returns None, and a plain let accepts only patterns that always fit, hence E0005. Write let Some((_, value)) = … else { return ""; };; if let or match work too.
- Reaching for
unwrap(), which compiles but panics on a line without= - Writing an
elseblock that yields a value instead of leaving withreturn,break,continueor a panic - Adding a type annotation, although the error is about a pattern that can fail, not about the type
- Why does
let (key, value) = pair;compile whilelet Some(v) = opt;does not? - When is a
matcha better fix here thanlet … else?
split_once('=') returns Option<(&str, &str)>: Some((before, after)) when it finds =, and None when it does not. The pattern Some((_, value)) fits only the first case, so it is refutable. A plain let accepts only irrefutable patterns — ones that fit any value of the type, such as a name or a tuple — because if the pattern does not fit, the program has nowhere to go. The compiler says exactly that: pattern `None` not covered — and suggests let...else itself.
let … else binds value for the rest of the function, and on None runs the else block, which must leave — here with return:
fn value_of(line: &str) -> &str {
let Some((_, value)) = line.split_once('=') else {
return "";
};
value
}
fn main() {
println!("{:?} {:?}", value_of("port=8080"), value_of("verbose"));
}The program prints "8080" "".
Two other working fixes:
match line.split_once('=') { Some((_, value)) => value, None => "" }— also panic-free, handy whenNoneneeds logic of its own.if let Some((_, value)) = line.split_once('=') { value } else { "" }— the same throughif let.
What does not work: unwrap() (the panic called `Option::unwrap()` on a `None` value on the line verbose) and an else { "" } block that does not leave the function: error[E0308]: `else` clause of `let...else` does not diverge.