How do I initialize a struct field which is a mutable reference to an Option?

ε祈祈猫儿з 提交于 2019-12-08 06:42:27

问题


How do I initialize a struct field which is a mutable reference to an Option<T>? Here is my struct:

pub struct Cmd<'a> {
    pub exec: String,
    pub args: &'a mut Option<Vec<String>>,
}

I tried to initialize this struct like this:

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

But I get the following error:

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`

What is the proper syntax?


回答1:


You just need to provide a mutable reference. Like this:

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


来源:https://stackoverflow.com/questions/44748656/how-do-i-initialize-a-struct-field-which-is-a-mutable-reference-to-an-option

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!