我正在学习rust,我想更好地了解这里发生了什么。我声明了以下内容:
pub struct SomeHandler {}
impl SomeHandler {
pub fn configure(&self, app: &App) {
app.subcommand(
SubCommand::with_name("server-status")
.about("Displays the status of the server")
);
}
pub fn check_match(&self, matches: &ArgMatches) -> bool {
matches.subcommand_matches("server-status").is_some()
}
pub fn handle(&self, arg_match: &ArgMatches) {
...
}
}然后在main.rs中,我这样命名它:
let mut app = App::new("My CLI")
.author("Author <author@email.com>")
.version("0.1.0")
.about("Command line interface app");
let myhandler = SomeHandler {};
myhandler.configure(&app);
let matches = app.get_matches();
let matched = myhandler.check_match(&matches);
if !matched {
eprintln!("None of the commands match the provided args.");
process::exit(1);
}
myhandler.handle(&matches);
process::exit(0);但我得到以下错误:
error[E0507]: cannot move out of `*app` which is behind a shared reference
--> cli\src\some_handler.rs:15:9
|
15 | app.subcommand(
| ^^^ move occurs because `*app` has type `App<'_, '_>`, which does not implement the `Copy` trait如何修复此错误?有没有更好的方法来处理这件事?我正在尝试在rust中构建一个具有多个命令和选项的命令行应用程序。我不想在一个文件中实现所有这些功能。这里可以遵循的好模式是什么?
任何帮助都是最好的,
谢谢,曼森
发布于 2021-03-22 06:31:35
subcommand()方法使用应用程序并返回一个新的应用程序。这很好地支持链接,但需要configure函数也接受一个对象,并返回一个对象:
pub fn configure(&self, app: App<'static, 'static>) -> App<'static, 'static> {
app.subcommand(
SubCommand::with_name("server-status")
.about("Displays the status of the server")
)
}
// and in main:
app = myhandler.configure(app);configure也可以接受一个引用,但那必须是一个mut引用,您必须调用mem::replace从引用中提取Clap,留下一个虚拟对象来代替它,最后将它分配回来。如果你真的很好奇,可以看看here。
https://stackoverflow.com/questions/66735838
复制相似问题