rust - 匹配枚举引用并返回 "match arms have incompatible types"中的字符串结果

标签 rust

如何在枚举引用上匹配?我正在使用返回对枚举的引用的依赖项,我需要读取枚举包含的值。在下面的示例中,我关心的是将 final_val 分配给 x:

fn main() {
    let test_string = String::from("test");
    let option: std::option::Option<String> = Some(test_string);
    let ref_option = &option;

    let final_val = match ref_option {
        Some(x) => x,
        _ => String::from("not Set"),
    };

    println!("{:?}", final_val);
}

如果我按照编译器的建议添加一个 & 到类型 Someref x:

fn main() {
    let test_string = String::from("test");
    let option: std::option::Option<String> = Some(test_string);
    let ref_option = &option;

    let final_val = match ref_option {
        &Some(ref x) => x,
        _ => String::from("not Set"),
    };

    println!("{:?}", final_val);
}

我收到以下错误,我不知道如何解决:

error[E0308]: match arms have incompatible types
  --> src\main.rs:6:21
   |
6  |       let final_val = match ref_option
   |  _____________________^
7  | |     {
8  | |         &Some(ref x) => x,
9  | |         _ => String::from("not Set" ),
   | |              ------------------------ match arm with an incompatible type

10 | |     };
   | |_____^ expected reference, found struct `std::string::String`
   |
   = note: expected type `&std::string::String`
              found type `std::string::String`

最佳答案

这是行不通的。在第一个 ARM 上返回 &String,在第二个 ARM 上返回 String

如果你克隆 x 它会工作,但不清楚你真正想要什么。

let final_val = match ref_option {
    &Some(ref x) => x.clone(),
    _ => String::from("not Set"),
};

Playground

编辑:

I would like it to be a string

然后提到的解决方案就是要走的路。然而,如果你真的不需要 String,你应该使用 tafia's solution。 :

let final_val = match *ref_option {
    Some(ref x) => x,
    _ => "not Set",
};

Playground

关于rust - 匹配枚举引用并返回 "match arms have incompatible types"中的字符串结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49441484/

相关文章:

ubuntu - GitHub Action 生成的 Cargo 构建工件不在本地执行

rust - "found struct ` ThereIsNoIteratorInRepetition `"尝试使用 `quote!` 在向量上重复时

rust - 为什么要尝试!()和?在不返回选项或结果的函数中使用时无法编译?

error-handling - 为什么 Rust 编译器不使用 From 特性将库错误转换为我的错误?

rust - 为什么不能在同一结构中存储值和对该值的引用?

module - 当有 main.rs 和 lib.rs 时 Rust 模块混淆

rust - 返回一个 str - Rust Lifetimes

rust - 为什么在 Rust 中改变拥有的值和借用的引用是安全的?

rust - 是否可以在 docs.rs 上查看功能文档?

rust - 从读取到写入的最简单方法是什么