Is it possible to combine two patterns, one with a match guard, in the same match arm?

雨燕双飞 提交于 2021-02-04 14:42:33

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!