我正在尝试编写这一小段代码,但我无法让它工作。我在 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`
我知道这个问题与 App
中 name
的生命周期有某种关系,但我不知道如何解决它。
最佳答案
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/