从函数返回闭包与在位定义不符

问题描述 投票:1回答:1

[当尝试使用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请注意,您可以在提交之间移动,以查看处于工作或失败状态的代码。

rust closures actix-web
1个回答
0
投票

然后使用impl Trait作为返回类型,除该值实现Trait之外的所有其他类型信息都将被擦除。

在这种特殊情况下,闭包move || get_user(&my_own_conf_clone)实现Fn() -> StringClone,但在返回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)
}
© www.soinside.com 2019 - 2024. All rights reserved.