i encountered a situation where i wanted to create a vector of tower::Services, and started with
let mut services: Vec<Box<dyn Service<StateRequest>>>; // didn't compile in my code
i was planning to loop over some stuff, create the service and add it to the vector.
i left out the associated type. However, the compiler required me to put type annotation for the associated type, but since i wasn't sure of the exact types, i tried my luck with '_' and surprisingly it compiled:
let mut services: Vec<Box<dyn Service<StateRequest, Response = _, Error = _, Future = _>>>; // compiles
But i find it strange cause i (think) i really didn't provide the compiler with any more information. So i would like to understand what's the difference and why the second piece of code compiles?
[Edit] Just to make things more concrete, i added sample code & error below:
use tower::{ServiceBuilder, Service, ServiceExt, BoxError};
pub struct A;
impl A {
// Associated types: Response & Error enough, (no Future)
pub fn build_service() -> impl Service<String, Response=String, Error=anyhow::Error> + 'static
{
let mut svc = ServiceBuilder::new();
let mut svc = svc.service_fn(
|req: String| { Box::pin(async move { Ok(req.clone()) } ) } );
svc
}
}
#[tokio::main]
async fn main() {
let mut services: Vec<Box<dyn Service<String>>> = Vec::new(); // Does not compile
let mut services: Vec<Box<dyn Service<String, Response=_, Error=_>>> = Vec::new(); // Does not compile, needs all 3
let mut services: Vec<Box<dyn Service<String, Response=_, Error=_, Future=_>>> = Vec::new(); // Compiles, but don't think i provide any more info than the above
for _ in 1..10 {
services.push(Box::new(A::build_service() ) );
}
}
Error:
error[E0191]: the value of the associated types `Error` (from trait `Service`), `Future` (from trait `Service`), `Response` (from trait `Service`) must be specified
--> src/trytowerbuild2.rs:24:35
|
24 | let mut services: Vec<Box<dyn Service<String>>> = Vec::new(); // Does not compile
| ^^^^^^^^^^^^^^^^ help: specify the associated types: `Service<String>, Response = Type, Error = Type, Future = Type>`