如何初始化一个对Option<T>
的可变引用的struct字段?这是我的结构:
pub struct Cmd<'a> {
pub exec: String,
pub args: &'a mut Option<Vec<String>>,
}
我尝试像这样初始化这个结构:
let cmd = Cmd {
exec: String::from("whoami"),
args: None,
};
但是我收到以下错误:
error[E0308]: mismatched types
--> src/main.rs:9:15
|
9 | args: None,
| ^^^^ expected mutable reference, found enum `std::option::Option`
|
= note: expected type `&mut std::option::Option<std::vec::Vec<std::string::String>>`
found type `std::option::Option<_>`
= help: try with `&mut None`
正确的语法是什么?
答案 0 :(得分:4)
您只需要提供一个可变引用。像这样:
let cmd = Cmd {
exec: String::from("whoami"),
args: &mut None,
};