我正在将match语句与.chars().next()一起使用,如果某个字符与某个字符匹配,则要将一个字符附加到字符串中。我正在尝试这样做

keyword.push(line.chars().next())

但出现错误:

expected type 'char' found type Option<<char>>

我该如何将其附加到我的字符串上?

最佳答案

就是这样:因为next()返回Option<char>,所以很可能返回None。您需要考虑这种情况...否则,您可能会引起 panic ,并且您的应用程序将退出。

因此,盲目且容易出错的方法是将其拆开:

keyword.push(line.chars().next().unwrap());

这可能会在某个时候崩溃。您想要的是对其进行重构,并确保其中存在某些内容:
match line.chars().next() {
    Some(c) => {
        if c == 'H' || c == 'W' {
             keyword.push(c);
        }
    },
    None => ()
}

正如Shepmaster在评论中指出的那样,可以将上述特定情况(我们只关心match的单个部分)简化为if let绑定(bind):
if let Some(c) = line.chars().next() {
    if c == 'H' || c == 'W' {
       keyword.push(c);
    }
}

就是说-您可以通过for循环进行迭代来免费获得所有功能:
for c in line.chars() {
    if c == 'H' || c == 'W' {
        keyword.push(c);
    }
}

Playground example

10-06 14:08
查看更多