如何解决无法移出共享引用后面的 *** (Clap)
我正在学习 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 命令行应用程序。我不想在一个文件中实现它。这里有什么好的模式可以遵循?
任何帮助都会很棒,
谢谢, 曼森
解决方法
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。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。