我如何针对 Option<String> 进行模式匹配? [英] How can I pattern match against an Option&lt;String&gt;?

查看:49
本文介绍了我如何针对 Option<String> 进行模式匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以直接匹配 Rust 中的 String:

I can straight-forwardly match a String in Rust:

let a = "hello".to_string();

match &a[..] {
    "hello" => {
        println!("Matches hello");
    }
    _ => panic!(),
}

如果我有一个选项类型,它就会失败:

If I have an option type, it fails:

match Some(a) {
    Some("hello") => {
        println!("Matches some hello");
    }
    _ => panic!(),
}

因为类型不匹配:

error[E0308]: mismatched types
 --> src/main.rs:5:14
  |
5 |         Some("hello") => {
  |              ^^^^^^^ expected struct `std::string::String`, found reference
  |
  = note: expected type `std::string::String`
             found type `&'static str`

我无法使用 [..] 技巧,因为我们有一个 Option.最好的那个到目前为止我想出的是:

I can't do the [..] trick because we have an Option. The best that I have come up with so far is:

match Some(a) {
    Some(b) => match (&b[..]) {
        "hello" => {
            println!("Matches some, some hello");
        }
        _ => panic!(),
    },
    None => panic!(),
}

它可以工作,但它的冗长很糟糕.

which works but is terrible for its verbosity.

在这种情况下,我的代码只是一个例子.我不控制 StringSome(String) 的创建——所以我不能像在我的例子中那样在现实中改变这种类型.

In this case, my code is just an example. I do not control the creation of either the String or the Some(String) — so I can't change this type in reality as I could do in my example.

还有其他选择吗?

推荐答案

这是 Rust 模式的一个已知限制.

It's a known limitation of Rust's patterns.

方法调用(包括像==这样的操作符的内部方法)会根据需要自动调用.deref(),所以String会自动转换进入 &str 以与文字进行比较.

Method calls (including internal methods for operators like ==) automatically call .deref() as needed, so String gets automagically turned into &str for comparisons with literals.

另一方面,模式在它们的比较中是相当直白的,并且发现String&str是不同的.

On the other hand, the patterns are quite literal in their comparisons, and find that String and &str are different.

有两种解决方案:

  1. 在匹配之前将 Option 更改为 Option<&str>:Some(a).as_deref()代码>.as_deref()as_ref() 的组合,它使 Option<&String>(防止移动)和 deref()/as_str() 然后明确地将其引用为 &str.

  1. Change Option<String> to Option<&str> before matching on it: Some(a).as_deref(). The as_deref() is a combo of as_ref() that makes Option<&String> (preventing move), and deref()/as_str() then unambiguously references it as a &str.

使用匹配保护:match Some(a) { Some(ref s) if s == "hello";=>... }.Some(ref s) 匹配任何 String,并将其捕获为 s: &String,然后您可以在 中进行比较if 守卫,它执行通常的灵活强制以使其工作.

Use match guard: match Some(a) { Some(ref s) if s == "hello" => … }. Some(ref s) matches any String, and captures it as s: &String, which you can then compare in the if guard which does the usual flexible coercions to make it work.

另见:

这篇关于我如何针对 Option<String> 进行模式匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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