Async fn name() -> impl SomeTrait { ... }

Hi,

I'm new to Rust and I have just started writing code after I have finished with Rust book. I have come across this kind of function and I didn't see this before. Can someone help me to understand this part of signature -> impl SomeTrait?
It is from one of the examples from Actix-web site and exact code looks like this:

async fn index() -> impl Responder {
    HttpResponse::Ok().body("Hello world")
}

I first time see this impl keyword inside of the function response signature.

It means that the return type is some concrete type (that isn't named) that implements the trait Responder. Often it's difficult or impossible to name certain types (for example, things parameterized over closures,) so instead you can just say that the return type implements a trait and that's all the caller can rely on.

1 Like

Hi,
Great, that is what I suppose it means, but I wasn't sure. So it is kind of generic return type which only need to have implemented exact trait...

Thanks for clearing this for me.

Not exactly generic, just unnamed but unique within the function and fixed for the lifetime of the program. So, you can't have two match arms or if/else branches returning different types, even if they implement the same trait, nor is it possible for different invocations of the function to return different types.

2 Likes

The reason people object to the word generic is that generic means the caller chooses the type. In this case you, the author of the function chose the type. The word for this is existential (i.e. there exists a type that fits here).

4 Likes

Great, thanks for detailed explanation. I have used generic in wrong context, I was meaning something similar like you explained, but still don't use right terminology for Rust... Thanks again.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.