Bas
Bas

Reputation: 2210

Returning struct with unknown generic type

I'm working on a small project in Rust where I want to have an app factory.

pub fn init_routes(cfg: &mut web::ServiceConfig) {
    cfg.service(index);
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let server = HttpServer::new(|| App::new().configure(init_routes));
    server.bind(("127.0.0.1", HTTP_PORT))?.run().await
}

In this case, it's only App::new().configure(init_routes). When the application grows, I'd like to add more routes and so on. It's also easy for testing.

When I put it in a function, like the following snippet, it appears to be returning App<actix_web::app_service::AppEntry> where the generic type is private (AppEntry).

fn create_app() {
    App::new().configure(init_routes)
}

I tried to just refer to -> App<_> with the Inferred type feature from Rust. This did not work. Can I create this app factory with the correct return type?

Upvotes: 1

Views: 213

Answers (1)

Joe Clay
Joe Clay

Reputation: 35847

AppEntry implements ServiceFactory<ServiceRequest>, so you should be able to make use of impl Trait here:

use actix_web::dev::{ServiceFactory, ServiceRequest};

fn create_app() -> App<impl ServiceFactory<ServiceRequest>> {
    App::new().configure(init_routes)
}

This won't help you if you actually need to name the type of the App somewhere, though.

Normally I'd be a bit wary of relying on a private type to implement a trait, in case a future version removes the implementation. But given that all of the other methods on App are bounded by that same trait, I don't think they could do this without it being a breaking change.

Upvotes: 3

Related Questions