是否可以在同一个火柴臂中组合两种模式,一种带有火柴守卫? [英] Is it possible to combine two patterns, one with a match guard, in the same match arm?

查看:58
本文介绍了是否可以在同一个火柴臂中组合两种模式,一种带有火柴守卫?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查一个字符串是否包含$"以及$"后面是否有内容:

我试过这个代码:

fn test(s: String) {匹配 s.find('$') {无 |(Some(pos) if pos == s.len() - 1) =>{expr1();}_ =>{ expr2();}}}

但它不编译:

<块引用>

error: 应为 `)` 或 `,` 之一,找到 `if`

是否不可能将 NoneSome 组合在一个 match-arm 中?

如果是这样,除了将expr1() 移动到一个单独的函数中之外,是否有一种简单的方法可以使其不重复?

解决方案

不可能让匹配保护(if 东西)只应用于一种模式替代(由 | 符号分隔的东西).每只手臂只有一个比赛后卫,并且适用于该手臂的所有模式.

但是,对于您的特定问题,有很多解决方案.例如:

if s.find('$').map(|i| i != s.len() - 1).unwrap_or(false) {expr2();} 别的 {expr1();}

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?

解决方案

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();
}

这篇关于是否可以在同一个火柴臂中组合两种模式,一种带有火柴守卫?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆