如何初始化对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`

正确的语法是什么?

最佳答案

您只需要提供可变的引用即可。像这样:

let cmd = Cmd {
    exec: String::from("whoami"),
    args: &mut None,
};

关于syntax - 如何初始化一个对Option的可变引用的struct字段?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44748656/

10-12 12:31
查看更多