函数参数中的类型不匹配

Type mismatch in function arguments

我正在尝试编写这一小段代码,但我无法让它工作。我在 Rust 方面的经验很少,尤其是在生命周期方面。

我已经用更小的脚本重现了错误:

fn main() {
    let app = App {
        name: &String::from("Davide"),
    };
    app.run();
}

struct App<'a> {
    name: &'a String,
}

impl<'a> App<'a> {
    fn run(self) {
        let result = App::validator_1(App::validator_2(App::box_command()))(self);
        println!("{}", result)
    }

    fn validator_1(next: Box<Fn(App) -> String>) -> Box<Fn(App) -> String> {
        Box::new(move |app: App| -> String { next(app) })
    }

    fn validator_2(next: Box<Fn(App) -> String>) -> Box<Fn(App) -> String> {
        Box::new(move |app: App| -> String { next(app) })
    }

    fn box_command() -> Box<Fn(App) -> String> {
        Box::new(App::command)
    }

    fn command(self) -> String {
        format!("Hello {}!", self.name)
    }
}

当我编译它时,我得到这个错误:

error[E0631]: type mismatch in function arguments
  --> src/main.rs:27:9
   |
27 |         Box::new(App::command)
   |         ^^^^^^^^^^^^^^^^^^^^^^ expected signature of `for<'r> fn(App<'r>) -> _`
...
30 |     fn command(self) -> String {
   |     -------------------------- found signature of `fn(App<'_>) -> _`
   |
   = note: required for the cast to the object type `for<'r> std::ops::Fn(App<'r>) -> std::string::String`

error[E0271]: type mismatch resolving `for<'r> <fn(App<'_>) -> std::string::String {App<'_>::command} as std::ops::FnOnce<(App<'r>,)>>::Output == std::string::String`
  --> src/main.rs:27:9
   |
27 |         Box::new(App::command)
   |         ^^^^^^^^^^^^^^^^^^^^^^ expected bound lifetime parameter, found concrete lifetime
   |
   = note: required for the cast to the object type `for<'r> std::ops::Fn(App<'r>) -> std::string::String`

我知道这个问题与 Appname 的生命周期有某种关系,但我不知道如何解决它。

command 函数的签名与 box_command 预期 return 的签名不匹配。

box_command 应具有以下正文:

fn box_command() -> Box<Fn(App) -> String> {
    Box::new(move |app: App| -> String { app.command() })
}

编译器期待一个 return 是 String 的调用。上述更改将允许将以下语句中的 self 作为 app 参数传递。因此 app.command() 满足调用链中的整个流程和 returns String

let result = App::validator_1(App::validator_2(App::box_command()))(self);