For me, a feature I'd really hope for is the elusive "if not let" (or however this gets named eventually), to let me escape the currently unavoidable clutches of Rust's rightwards drift and accruing mental context.
guard let x = ... else {
// must not fall through, so a return, break, throw, non-returning function call, etc. is required
}
// do something with x let x = match foo {
Some(x) => ...,
None => return // or break, etc.
};
// do something with x
(This is assuming that you don't want to propagate an error or panic, which could be more easily done with `foo?` or `foo.unwrap()` respectively.) // want to do this
if not let Some("pattern") = val {
doSomething();
}
// can instead do
if !matches!(val, Some("pattern")) {
doSomething();
} if !matches!(val, Some(let x)) let input: Option<usize> = Some(1);
if let Some(value) != input {
return 0;
}
// use value; such that value: usize = 1 let input: Option<usize> = Some(1);
let value = match input {
Some(x) => x,
_ => return 0,
};
// use value; such that value: usize = 1The 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.