[当尝试使用actix-web实现一个简单的Web服务器应用程序时,我遇到了不知道如何解释的Rust闭包的明显不一致的行为。
我有以下代码:
use actix_web::{web, App, HttpServer};
#[derive(Clone)]
struct Config {
val1: String,
val2: String,
val3: String,
}
fn main() {
let conf = Config {
val1: "just".to_string(),
val2: "some".to_string(),
val3: "data".to_string(),
};
HttpServer::new(move ||
App::new().configure(create_config(&conf))
)
.bind("127.0.0.1:8088")
.unwrap()
.run()
.unwrap();
}
fn create_config<'a>(conf: &'a Config) -> impl FnOnce(&mut web::ServiceConfig) + 'a {
move |app: &mut web::ServiceConfig| {
// Have to clone config because web::get().to by definition requires
// its argument to have static lifetime, which is longer than 'a
let my_own_conf_clone = conf.clone();
app.service(
web::scope("/user")
.route("", web::get().to(move || get_user(&my_own_conf_clone)))
);
}
}
fn get_user(conf: &Config) -> String {
println!("Config {} is {} here!", conf.val3, conf.val1);
"User McUser".to_string()
}
此代码有效。注意我传递给web::get().to
的闭包。我使用它将Config
对象传递到get_user
,并根据需要将web::get().to
呈现给没有参数的函数。在这一点上,我决定将闭包生成移到一个单独的函数中:
fn create_config<'a>(conf: &'a Config) -> impl FnOnce(&mut web::ServiceConfig) + 'a {
move |app: &mut web::ServiceConfig| {
app.service(
web::scope("/user")
.route("", web::get().to(gen_get_user(conf)))
);
}
}
fn gen_get_user(conf: &Config) -> impl Fn() -> String {
let my_own_conf_clone = conf.clone();
move || get_user(&my_own_conf_clone)
}
fn get_user(conf: &Config) -> String {
println!("Config {} is {} here!", conf.val3, conf.val1);
"User McUser".to_string()
}
此代码无法编译,并出现以下错误:
error[E0277]: the trait bound `impl std::ops::Fn<()>: actix_web::handler::Factory<_, _>` is not satisfied
--> src/main.rs:30:39
|
30 | .route("", web::get().to(gen_get_user(conf)))
| ^^ the trait `actix_web::handler::Factory<_, _>` is not implemented for `impl std::ops::Fn<()>`
为什么它在第二种情况下失败但在第一种情况下没有失败?为什么在第一种情况下满足特征Factory
但在第二种情况下不满足?可能是工厂的错误(来源为here)吗?在这种情况下,是否有其他方法可以返回关闭操作?您还可以建议其他方法吗? (请注意,Factory
不是公开的,所以我自己不能直接实现它)
[如果您想四处浏览代码,请在此处输入:https://github.com/yanivmo/rust-closure-experiments请注意,您可以在提交之间移动,以查看处于工作或失败状态的代码。
然后使用impl Trait
作为返回类型,除该值实现Trait
之外的所有其他类型信息都将被擦除。
在这种特殊情况下,闭包move || get_user(&my_own_conf_clone)
实现Fn() -> String
和Clone
,但在返回Clone
之后将被擦除。
但是由于Factory
是为Fn() -> String + Clone
实现的,而不是为Fn() -> String
返回值,因此不再实现工厂。
可以通过将gen_get_user
更改为]来解决>
fn gen_get_user(conf: &Config) -> impl Fn() -> String + Clone{
let my_own_conf_clone = conf.clone();
move || get_user(&my_own_conf_clone)
}