簡體   English   中英

如何初始化對Option的可變引用的struct字段?

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

如何初始化作為對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,
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM