简体   繁体   English

我如何追加期权 <char> 到一个字符串?

[英]How would I append an Option<char> to a string?

I am using a match statement with .chars().next() and want to append a character to a string if it matches a certain character. 我正在将match语句与.chars().next() ,如果某个字符与某个字符match.chars().next()将一个字符附加到字符串中。 I am trying to do so like this 我正在尝试这样做

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

but get an error: 但出现错误:

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

How would I go about appending this onto my string? 我如何将其附加到我的字符串上?

Well, thats the thing: because next() returns an Option<char> , its possible that it returns None . 就是这样:因为next()返回Option<char> ,所以很可能返回None You need to account for that scenario... otherwise you'll likely cause a panic and your application will exit. 您需要考虑这种情况...否则,您可能会引起恐慌,并且您的应用程序将退出。

So, the blind and error-prone way is to unwrap it: 因此,盲目且容易出错的方法是将其拆开:

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

That will likely crash at some point. 这可能会在某个时候崩溃。 What you want is to destructure it and make sure there's something there: 您想要的是对其进行重构,并确保其中存在某些内容:

match line.chars().next() {
    Some(c) => {
        if c == 'H' || c == 'W' {
             keyword.push(c);
        }
    },
    None => ()
}

As Shepmaster points out in the comments, the particular scenario above (where we only care about a single arm of the match ) can be condensed to an if let binding: 正如Shepmaster在评论中指出的那样,可以将上述特定情况(我们只关心match一个分支)简化为if let绑定:

if let Some(c) = line.chars().next() {
    if c == 'H' || c == 'W' {
       keyword.push(c);
    }
}

That said - you get this all for free by iterating via a for loop: 就是说-您可以通过for循环进行迭代来免费获得所有功能:

for c in line.chars() {
    if c == 'H' || c == 'W' {
        keyword.push(c);
    }
}

Playground example 操场上的例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM