简体   繁体   English

如何初始化对Option的可变引用的struct字段?

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

How do I initialize a struct field which is a mutable reference to an Option<T> ? 如何初始化作为对Option<T>的可变引用的struct字段? 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? 正确的语法是什么?

You just need to provide a mutable reference. 您只需要提供可变的参考即可。 Like this: 像这样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM