问题
I want to check if a string contains '$' and if there is something after the '$':
I tried this code:
fn test(s: String) {
match s.find('$') {
None | (Some(pos) if pos == s.len() - 1) => {
expr1();
}
_ => { expr2(); }
}
}
But it doesn't compile:
error: expected one of `)` or `,`, found `if`
Is it impossible to combine None
and Some
in one match-arm?
If so, is there a simple way to not duplicate expr1()
except moving it into a separate function?
回答1:
It is impossible to have the match-guard (the if
thingy) apply to only one pattern alternative (the things separated by |
symbols). There is only one match-guard per arm and it applies to all patterns of that arm.
However, there are many solutions for your specific problem. For example:
if s.find('$').map(|i| i != s.len() - 1).unwrap_or(false) {
expr2();
} else {
expr1();
}
来源:https://stackoverflow.com/questions/42355502/is-it-possible-to-combine-two-patterns-one-with-a-match-guard-in-the-same-matc