3 ms·
Lol it would be kinda funny to have this: let input: Option<usize> = Some(1); if let Some(value) != input { return 0; } // use value; s
by yazaddaruvala 6y ago
Lol it would be kinda funny to have this:
let input: Option<usize> = Some(1);
if let Some(value) != input {
return 0;
}
// use value; such that value: usize = 1
- nybble41 6y agoWe already have something close: let input: Option<usize> = Some(1); let value = match input { Some(x) => x, _ => return 0, }; // use value; such that value: usize = 1
- NobodyNada 6y agoThat works, but it's clunky enough that it defeats the purpose of writing guard statements IMO. It's not hard to understand, but it's also not possible to figure out what it means at-a-glance. I have to stare at it for a few seconds to try to figure out where all control flow is going to go -- it has two levels of nested subexpressions, along with branches that appear similar but do very different things (returning a value from the expression vs. from the function). The point of a 'guard' clause is to visually distinguish between the "expected" and "unexpected" case. When I see a guard statement: let input: Option<usize> = Some(1); guard let Some(value) = input else { return 0; } // use value; such that value: usize = 1 I immediately know that the rest of the function expects input to contain a value, and that whatever is after the 'else' is some kind of error handler. Your match statement might have the same effect functionally, but visually it's confusing because it's not immediately obvious which branch is the happy-path. I'd rather read a function containing ten guard clauses than a function containing ten of those matches.
- freeopinion 6y agoSome(1).unwrap_or(0)
- Quekid5 6y agoReturn 0 is different from using 0 in the rest of the function body.