Reputation: 51
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?
Upvotes: 1
Views: 2253
Reputation: 58735
You just need to provide a mutable reference. Like this:
let cmd = Cmd {
exec: String::from("whoami"),
args: &mut None,
};
Upvotes: 4