rust - 函数参数中的类型不匹配

标签 rust lifetime

我正在尝试编写这一小段代码,但我无法让它工作。我在 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 预期返回的不匹配。

box_command 应具有以下主体:

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

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

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

关于rust - 函数参数中的类型不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49894224/

相关文章:

rust - 跨闭包执行缓存结果 : the size for values of type `dyn Fn(u64) -> ...` cannot be known at compilation time

rust - C 字符串中缺少第一个字符

data-structures - 如何确保 Rust 向量仅包含交替类型?

google-app-engine - GAE 内存缓存生命周期非常短

rust - 如何将生命限制在使用rust 的封闭环境中?

asp.net-mvc-3 - controller 'TestController' 单个实例不能用于处理多个请求

rust - 为什么我的测试会更改字节数组的长度?

Rust 和 C/C++ 指针访问结构中值的比较

struct - 如何为&Struct实现Default?

reference - 有没有办法返回对函数中创建的变量的引用?