我正在try 将一个if let条件与一个常规布尔条件相链接.

if let Some(char_first_index) = char_info.first_index_in_string && !char_info.repeats_in_string

然而,当我试图运行它时,我得到了一个编译器问题,将我重定向到https://github.com/rust-lang/rust/issues/53667.这个RFC主要处理链接If‘s.虽然这里提到了一个问题,https://github.com/rust-lang/rfcs/blob/master/text/2497-if-let-chains.md#dealing-with-ambiguity提到了在链接If let和Boolans的情况下处理歧义的问题.

if let PAT = EXPR && EXPR { .. }
// It can either be parsed as (1):

if let PAT = (EXPR && EXPR) { .. }
// or instead as (2):

if (let PAT = EXPR) && EXPR { .. }

重新排序以避免这种歧义:

if !char_info.repeats_in_string && let Some(char_first_index) = char_info.first_index_in_string

或添加方括号:

if !char_info.repeats_in_string && (let Some(char_first_index) = char_info.first_index_in_string) 

没有解决问题,我仍然收到相同的编译器错误.我不确定刚才提到的RFC是否被取消了(抱歉,我对GitHub不是很有经验).然而,目前我能找到的唯一解决方案是使用两个独立的IF条件:

if !char_info.repeats_in_string {
    if let Some(char_first_index) = char_info.first_index_in_string {

或使用匹配块

match (char_info.repeats_in_string, char_info.first_index_in_string) {
    (false, Some(char_first_index)) => { 
        // former contents of if block
    },
    _ => {}
}

有没有一种方法,或者让我错过的if块工作,或者有一个比多个if/单臂匹配块更优雅的解决方案?谢谢,

推荐答案

您可以将匹配版本转换为if-let表达式:

if let (false, Some(char_first_index)) =
    (char_info.repeats_in_string, char_info.first_index_in_string)
{
    // former contents of if block
}

事实上,当给出匹配结果时,Clippy会建议进行精确的转换:

warning: you seem to be trying to use `match` for destructuring a single pattern. Consider using `if let`
  --> src\lib.rs:7:5
   |
7  | /     match (char_info.repeats_in_string, char_info.first_index_in_string) {
8  | |         (false, Some(char_first_index)) => {
9  | |             // former contents of if block
10 | |         }
11 | |         _ => {}
12 | |     }
   | |_____^
   |
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#single_match
   = note: `#[warn(clippy::single_match)]` on by default
help: try
   |
7  ~     if let (false, Some(char_first_index)) = (char_info.repeats_in_string, char_info.first_index_in_string) {
8  +         // former contents of if block
9  +     }
   |

Rust相关问答推荐

如何容器化Linux上基于Rust的Windows应用程序的编译过程?

抽象RUST中的可变/不可变引用

如果成员都实现特征,是否在多态集合上实现部分重叠的特征?

S,一般性状和联想型性状有什么不同?

如何在递归数据 struct 中移动所有权时变异引用?

如何高效地将 struct 向量中的字段收集到单独的数组中

循环访问枚举中的不同集合

无法将 rust 蚀向量附加到另一个向量

通过异常从同步代码中产生yield 是如何工作的?

pyO3 和 Panics

分配给下划线模式时会发生什么?

如何将 Rust 字符串转换为 i8(c_char) 数组?

在运行时在 Rust 中加载字体

为什么可以在迭代器引用上调用 into_iter?

如何在 Rust 中将 UTF-8 十六进制值转换为 char?

为什么具有 Vec 变体的枚举没有内存开销?

当我不满足特征界限时会发生什么?

为什么这个闭包没有比 var 长寿?

为什么我可以从读取的可变自引用中移出?

有没有比多个 push_str() 调用更好的方法将字符串链接在一起?