问题描述

我正在try 将选项字符串与match语句匹配

let option_string = Some(String::from("Bob"));
    
match option_string {
  Some("Mike") => false,
  Some("Bob") => true,
  _ => false,
}

很明显,错误为expected struct 'String, found '&str'.

我试着把它改成字符串

Some("Mike".to_string()) => false

// Or
Some(String::from("Mike")) => false

但面临一个不同的错误:'fn' calls are not allowed in patterns


唯一有效的方法是将Mike放入Some之前的变量中

let mike = String::from("Mike");

// and in match
Some(mike) => true,

问题

有一种更优雅的方法来匹配match个具有Option个值的情况下的String个而不是字符串文字?

但它看起来不够优雅.但这是否只是一种不创建额外变量或函数的可能方法?

推荐答案

let mike = String::from("Mike");

// and in match
Some(mike) => true,

恐怕这实际上是一个误解.match表达式的左侧不允许有变量.在左侧有一个名称实际上会创建一个包含匹配内容的新变量.因此,match子句中的mike变量匹配everything,然后携带匹配的String;它是not,与外部mike变量相同.

请注意以下代码示例:

fn main() {
    let option_string = Some(String::from("Bob"));

    // Note how this line gets the compiler warning "unused variable".
    // You could leave this line out completely and it would still
    // compile.
    let mike = String::from("Mike");

    let result = match option_string {
        Some(mike) => {
            println!("Matched 'Mike': {}", mike);
            true
        }
        _ => false,
    };

    println!("{:?}", result);
}
Matched 'Mike': Bob
true

通常,您只能匹配编译时常量.如果要比较两个变量,则必须使用if.


解决方案

也就是说,您的第一个示例很容易修复:

fn main() {
    let option_string = Some(String::from("Bob"));

    let result = match option_string.as_deref() {
        Some("Mike") => false,
        Some("Bob") => true,
        _ => false,
    };

    println!("{:?}", result);
}
true

请注意.as_deref(),它从Option<String>中borrow 了Option<&str>,使其与字符串文字匹配表达式兼容.

Rust相关问答推荐

trait声明中的生命周期参数

在跨平台应用程序中使用std::OS::Linux和std::OS::Windows

在自定义序列化程序中复制serde(With)的行为

无法从流中读取Redis请求

Tokio_Postgres行上未显示退回特性的生存期,且生命周期 不够长

`RwLockWriteGuard_,T`不实现T实现的特征

异步函数返回的future 生存期

将serde_json读入`VEC<;T&>;`( rust 色)时出现问题

考虑到Rust不允许多个可变引用,类似PyTorch的自动区分如何在Rust中工作?

是否可以使用Serde/Rust全局处理无效的JSON值?

类型生命周期绑定的目的是什么?

RUST 中的读写器锁定模式

为什么 Rust 需要可变引用的显式生命周期而不是常规引用?

使用占位符获取用户输入

为什么某些类型参数仅在特征边界中使用的代码在没有 PhantomData 的情况下进行编译?

Rust 中的 Option as_ref 和 as_deref 有什么不同

`移动||异步移动{...}`,如何知道哪个移动正在移动哪个?

`use std::error::Error` 声明中断编译

将 (T, ()) 转换为 T 安全吗?

Rust 为什么 (u32, u32) 的枚举变体的大小小于 (u64)?