3 ms·
It's binding a variable `even`, and then using a pattern guard to conditionally take that arm depending on the value of `even`; it's (basically) the same as
by dbaupp 12y ago
It's binding a variable `even`, and then using a pattern guard to conditionally take that arm depending on the value of `even`; it's (basically) the same as
match val {
even => {
if even % 2 == 0 {
Some(even)
} else {
None
}
}
_ => None
}
which is an absurd construct (and the example pretty absurd too). It should be written as just
if val % 2 == 0 {
Some(val)
} else {
None
}
or, if you really like the formatting a match provides, just avoid creating a new name binding
match () {
_ if val % 2 == 0 => Some(val),
_ => None
}
`match` and pattern guards make far more sense when not just binding directly to a single variable like that, e.g.
let val: Option<int> = ...;
match val {
// even
Some(x) if x % 2 == 0 => Some(x),
// odd
Some(x) => Some(x + 1),
None => None
}
(Of course this may still be clearer using `.map` instead `match` but it's a better example than the original one.)