即使在阅读了有关引用所有权和借用的章节之后,我仍然无法理解以下代码中的一些内容,从而有效地阻止了我从clap::App调用多个方法!
extern crate clap;
use clap::App;
fn main() {
let mut app =
App::new("name me").args_from_usage("<input_file> 'Sets the input file to use'");
let matches = app.get_matches();
app.print_help();
println!(
"Using input file: {}",
matches.value_of("input_file").unwrap()
);
}编译此代码将导致:
error[E0382]: use of moved value: `app`
--> src/main.rs:9:5
|
8 | let matches = app.get_matches();
| --- value moved here
9 | app.print_help();
| ^^^ value used here after move
|
= note: move occurs because `app` has type `clap::App<'_, '_>`, which does not implement the `Copy` traitapp.get_matches()要求借用所有权,因此app必须是mut。一旦函数返回,所有权到哪里去了?app仍然拥有对象的所有权,但是编译器有不同的观点。如何才能得到匹配,并且仍然有效地调用另一个方法,例如print_help on app?
发布于 2016-12-03 19:30:37
fn get_matches(self) -> ArgMatches<'a>这按值取self,也是这样说的,因为它消耗了该值;之后您不能对它调用任何方法。这方面没有什么可做的;想必作者对此有很好的理由。
现在回顾一下App::print_help
fn print_help(&mut self) -> ClapResult<()>它需要一个引用(碰巧是可变的)。您不必转移所有权才能调用此方法。
如果我的理解正确,
app.get_matches()要求借用所有权,因此应用程序必须是mut。一旦函数返回,所有权到哪里去了?
你没有正确地理解,在多个维度。
get_matches消耗了这个价值,它什么都不借。我怎样才能得到匹配,并且仍然有效地调用另一种方法,比如app上的
print_help?
显然的解决办法是克隆原始对象,生成第二个值。然后,您可以使用一个值,并仍然调用第二个值的方法。
基本上,听起来你在尝试做一些图书馆阻止你去做的事情。也许您应该重新评估您的目标和/或检查库的预期用途。例如,get_matches会在用户请求时自动显示帮助文本,那么您的代码为什么要这样做呢?
来自鼓掌问题追踪器
你有几个选择。您可以使用
AppSettings::ArgRequiredElseHelp,也可以通过使用App::get_matches_from_safe_borrow来防止移动发生。
https://stackoverflow.com/questions/40951538
复制相似问题