async-stream icon indicating copy to clipboard operation
async-stream copied to clipboard

Type annotations

Open dbrgn opened this issue 5 years ago • 4 comments

Often I get compile errors when the compiler cannot deduce the type when using try_stream!:

error[E0698]: type inside `async fn` body must be known in this context
   --> src/server.rs:213:18
    |
213 |       let stream = try_stream! {
    |  __________________^
214 | |         while let Some(chunk) = body.data().await {
215 | |             let chunk = chunk?;
216 | |             trace!("Body: {:?}", &chunk);
...   |
219 | |         }
220 | |     };
    | |_____^ cannot infer type for type parameter `E` declared on the enum `Result`

This can be resolved by moving the code into a function that returns the appropriate generic type. However, is it also possible to put a type annotation somewhere? (impl T doesn't seem to work for annotating the type of a local variable.)

dbrgn avatar Aug 06 '20 09:08 dbrgn

I don't see you yielding anywhere in this example.

carllerche avatar Aug 06 '20 16:08 carllerche

Unfortunately, "terrible compilation errors" is going to be a limitation of this crate & the macro strategy. Doing better on the compilation error front will require rustc to provide stream generators.

Sorry :(

carllerche avatar Aug 06 '20 16:08 carllerche

Sorry, the yield was in the part that was omitted in the error message :slightly_smiling_face:

Sure, that's fine, I just wondered whether there's an easy way to annotate the return type, so that I won't have to create a helper function. But helper functions work just fine.

dbrgn avatar Aug 06 '20 19:08 dbrgn

I managed to annotate the return type by writing this:

let stream = try_stream! {
    //...
};
let _: &dyn Stream<Item=Result<_, MyError>> = &stream;

Not the prettiest code, but it gets the job done and looks better than the auxiliary function. I've checked the generated assembly and it has zero cost.

rodrigorc avatar Sep 28 '22 20:09 rodrigorc