E1038#
Useless guard because the pattern is irrefutable. A pattern is irrefutable means it accepts all possible input. If a pattern in guard let accepts all possible input, then it will always continue on, making the guard useless.
One common mistake is, say if you want to return early on some condition, and
continues otherwise. However, since the pattern matching is evaluated from first
to last, the pattern after guard let
will be first evaluated and will always
be success. Therefore, such code will not work since all control will continue
on and never returns early.
Erroneous example#
fn f(input : Int?) -> Int {
guard let _ = input else {
Some(_..<0) => abort("Invalid input")
}
3
}
fn main {
ignore(f(None))
}
Suggestion#
If you want all possible control flows goes through, then you can remove the guard and just use let expression.
fn f(input : Int?) -> Int {
let _ = input
3
}
If you fail into the early return mistake, you can switch to match
expression:
fn f(input : Int?) -> Int {
match input {
Some(_..<0) => abort("Invalid input")
_ => ()
}
3
}