相关疑难解决方法(0)

从Option <String>转换为Option <&str>

我经常Option<String>从计算中获得一个,我想使用这个值或默认的硬编码值.

这对于一个整数来说是微不足道的:

let opt: Option<i32> = Some(3);
let value = opt.unwrap_or(0); // 0 being the default
Run Code Online (Sandbox Code Playgroud)

但是使用a String和a &str,编译器会抱怨类型不匹配:

let opt: Option<String> = Some("some value".to_owned());
let value = opt.unwrap_or("default string");
Run Code Online (Sandbox Code Playgroud)

这里的确切错误是:

error[E0308]: mismatched types
 --> src/main.rs:4:31
  |
4 |     let value = opt.unwrap_or("default string");
  |                               ^^^^^^^^^^^^^^^^
  |                               |
  |                               expected struct `std::string::String`, found reference
  |                               help: try using a conversion method: `"default string".to_string()`
  |
  = note: expected type `std::string::String`
             found type `&'static str`
Run Code Online (Sandbox Code Playgroud)

一种选择是将字符串切片转换为拥有的String,如rustc所示:

let value …
Run Code Online (Sandbox Code Playgroud)

rust

56
推荐指数
4
解决办法
7801
查看次数

匹配枚举引用并返回字符串导致“匹配臂具有不兼容的类型”

我如何match在枚举引用上?我使用的依赖项返回对枚举的引用,我需要读取枚举包含的值。在下面的例子中,我关心的事情是分配final_valx

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);
}
Run Code Online (Sandbox Code Playgroud)

如果我遵循编译器的建议并&在类型中添加 aSomeref 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"),
    }; …
Run Code Online (Sandbox Code Playgroud)

rust

-1
推荐指数
1
解决办法
1076
查看次数

标签 统计

rust ×2