struct - 如何将 clap::ArgMatches 存储在结构中?
问题描述
我正在尝试存储clap::ArgMatches
在这样的结构中:
struct Configurator {
cli_args: ArgMatches,
root_directory: String
}
我收到的错误是:
error[E0106]: missing lifetime specifier
--> src/configurator.rs:5:15
|
5 | cli_args: ArgMatches,
| ^^^^^^^^^^ expected named lifetime parameter
|
help: consider introducing a named lifetime parameter
|
4 | struct Configurator<'a> {
5 | cli_args: ArgMatches<'a>,
|
我尝试了错误输出中给出的建议解决方案,但这似乎会导致不同的错误。
这里有更多的上下文:
extern crate clap;
use clap::{Arg, App, ArgMatches};
struct Configurator {
cli_args: ArgMatches,
root_directory: String
}
impl Configurator {
pub fn build() -> Configurator {
let configurator = Configurator {};
// returns ArgMatches apparently
let cli_args = App::new("Rust Web Server")
.version("0.0.1")
.author("Blaine Lafreniere <brlafreniere@gmail.com>")
.about("A simple web server built in rust.")
.arg(Arg::with_name("root_dir")
.short("r")
.long("root_dir")
.value_name("ROOT_DIR")
.help("Set the root directory that the web server will serve from.")
.takes_value(true))
.get_matches();
configurator.cli_args = cli_args;
}
}
解决方案
正如错误消息所暗示的,您必须将命名的生命周期说明符添加到Configurator
. 这是因为ArgMatches
保存了对值的引用,所以你必须告诉 Rust 这些引用会存在多久:
struct Configurator<'a> {
cli_args: ArgMatches<'a>,
root_directory: String
}
您必须对impl
块执行相同的操作:
impl<'a> Configurator<'a> {
pub fn build() -> Configurator<'a> {
// ...
}
}
您的代码的另一个问题是,在 Rust 中,您必须在实例化结构时初始化所有字段:
// this doesn't work
let config = Configurator {}
// but this does
let config = Configurator {
cli_args: cli_args,
root_directory: "/home".to_string(),
};
最后,您必须Configurator
从函数返回:
pub fn build() -> Configurator<'a> {
let cli_args = App::new("Rust Web Server")
.version("0.0.1")
.author("Blaine Lafreniere <brlafreniere@gmail.com>")
.about("A simple web server built in rust.")
.arg(
Arg::with_name("root_dir")
.short("r")
.long("root_dir")
.value_name("ROOT_DIR")
.help("Set the root directory that the web server will serve from.")
.takes_value(true),
)
.get_matches();
return Configurator {
cli_args: cli_args,
root_directory: "/home".to_string(),
};
}
这是一个可运行的示例。
推荐阅读
- html - Angular HTML字符串 - 重命名属性
- ruby-on-rails - 无法在 Windows 10 的 Rails 上连接到“localhost”(10061)上的 MySQL 服务器
- javascript - 'callCounter' 已声明,但其值从未被读取
- javascript - 使用多个嵌套的 If Else 语句是一种不好的做法吗?
- c# - CefSharp.WinForms 81.3.100 示例应用程序崩溃
- odoo - 如何从网站访问自定义模块(针对门户用户)[odoo13]
- graphql - 如何从 GitLab 中选择项目列表?
- java-8 - 使用java 8更新列表中的地图内的值
- php - 使用 Laravel 任务调度的通知
- snowflake-cloud-data-platform - 带有别名的子查询失败,标识符为“T1.C0”