trait Responder{
}
struct App;
impl App {
fn new() -> Self {
Self {}
}
fn service<T, B>(&self, routes: T) -> Self where T: Fn()-> impl Responder {
Self {}
}
}
struct Routes {
data:String,
}
impl Responder for Routes{
}
fn routes() -> impl Responder {
Routes {
data: "Hello".to_string()
}
}
fn main() {
// let new_routes = routes;
App::new().service(routes);
}
How do I pass a function a parameter that return impl Trait
or in my case impl Responder
.
The error that it gives is: impl Trait
not allowed outside of function and inherent method return types.
You can't - the docs (and the error) are explicit that the impl trait
syntax can only be used when returning a value from a function to help the compiler deduce things (about a value). In your case you are trying to say something about a generic type, which is not the same and thus this syntax cannot be used.
Instead, you have to specify a type, in your case a generic one with a constraint:
fn service<T, B>(&self, routes: T) -> Self where T: Fn()->B, B: Responder
assuming you did not need B
for something else. Note routes
returns a value with a specific type, not an impl trait
, and this type is what you are trying to write out.