首页 文章

clap :: App上的方法调用多次移动所有权

提问于
浏览
2

即使在阅读了关于引用所有权和借用的章节之后,我也无法理解以下代码中的一些内容,从而有效地阻止我从 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` trait
  • 如果我理解正确, app.get_matches() 要求借用所有权,因此 app 必须是 mut . 一旦函数返回,所有权在哪里?

  • 我以为 app 仍然拥有该对象的所有权,但编译器有不同的意见 .

我如何获得匹配,并有效地仍然调用另一个方法,例如 app app

1 回答

  • 1

    阅读function signature for App::get_matches

    fn get_matches(self) -> ArgMatches<'a>
    

    这取值为 self ,也表示消耗该值;之后你不能在它上面调用任何方法 . 关于这一点没有什么可做的;据推测,作者对此有充分的理由 .

    现在点评App::print_help

    fn print_help(&mut self) -> ClapResult<()>
    

    它需要一个引用(这恰好是可变的) . 您无需转移所有权即可调用此方法 .


    如果我理解正确,app.get_matches()要求借用所有权,因此app必须是mut . 一旦函数返回,所有权在哪里?

    您无法正确理解多维度 .

    • get_matches 消耗该值,它不借用任何东西 .

    • 一个值不需要是可变的借用 .

    • 当你借用东西时,所有权并不是为什么它被称为借贷 .

    我怎样才能获得匹配,并且仍然有效地调用另一种方法,例如app上的print_help?

    你没有 . 显而易见的解决方法是克隆原始对象,生成第二个值 . 然后,您可以使用一个值,仍然可以在第二个值上调用方法 .


    基本上,听起来你正试图做一些图书馆阻止你做的事情 . 也许您应该重新评估您的目标和/或查看库的预期用途 . 例如, get_matches 将在用户请求时自动显示帮助文本,那么为什么您的代码会尝试这样做呢?

    来自Clap issue tracker

    你有几个选择 . 您可以使用AppSettings :: ArgRequiredElseHelp,也可以使用App :: get_matches_from_safe_borrow来防止发生这种情况 .

相关问题