我经常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) use std::fs::File;
use std::io::Read;
pub struct Foo {
maybe_file: Option<File>,
}
impl Foo {
pub fn init(&mut self) {
self.maybe_file = Some(File::open("/proc/uptime").unwrap());
}
pub fn print(&mut self) {
let mut file = self.maybe_file.unwrap();
let mut s = String::new();
file.read_to_string(&mut s).unwrap();
println!("Uptime: {}", s);
}
}
fn main() {}
Run Code Online (Sandbox Code Playgroud)
编译这将给我:
error[E0507]: cannot move out of borrowed content
--> src/main.rs:14:24
|
14 | let mut file = self.maybe_file.unwrap();
| ^^^^ cannot move out of borrowed content
Run Code Online (Sandbox Code Playgroud)
为什么会这样?我该怎么做才能解决它?