相关疑难解决方法(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
查看次数

标签 统计

rust ×1