如何初始化一个对Option的可变引用的struct字段? [英] How do I initialize a struct field which is a mutable reference to an Option?

查看:252
本文介绍了如何初始化一个对Option的可变引用的struct字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何初始化对Option<T>的可变引用的struct字段?这是我的结构:

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,
};

但是出现以下错误:

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`

正确的语法是什么?

推荐答案

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

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

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

这篇关于如何初始化一个对Option的可变引用的struct字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆