rmanoka / async-scoped

A scope for async_std and tokio to spawn non-static futures
117 stars 14 forks source link

Compilation error, failed inference on closure #10

Closed Verdagon closed 2 years ago

Verdagon commented 2 years ago

If I compile the example program, the compiler fails to infer the closure's type:

use async_scoped::*;

#[async_std::main]
async fn main() {
    scoped_futures().await;
}

async fn scoped_futures() {
    let not_copy = String::from("hello");
    let not_copy_ref = &not_copy;

    let ((), vals) = Scope::scope_and_block(|s| {
        for _ in 0..10 {
            let proc = || async {
                println!("Running a task! {:?}", not_copy_ref);
            };
            s.spawn(proc());
        }
    });

    assert_eq!(vals.len(), 10);
}
$ cargo build
    Updating crates.io index
   Compiling async-scoped v0.7.0
   Compiling rustfearlessstructured v0.1.0 (/Users/verdagon/RustFearlessStructuredConcurrency)
error[E0282]: type annotations needed for `&mut async_scoped::Scope<'_, (), Sp>`
  --> src/main.rs:12:46
   |
12 |     let ((), vals) = Scope::scope_and_block(|s| {
   |                                              ^ consider giving this closure parameter the explicit type `&mut async_scoped::Scope<'_, (), Sp>`, where the type parameter `Sp` is specified

error: aborting due to previous error

For more information about this error, try `rustc --explain E0282`.
error: could not compile `rustfearlessstructured`

To learn more, run the command again with --verbose.

(reproduced in https://github.com/Verdagon/RustFearlessStructuredConcurrency/blob/33019c43cd95d5ad2152590263739549d38ab869/src/main.rs)

Verdagon commented 2 years ago

Temporary workaround shown in https://github.com/Verdagon/RustFearlessStructuredConcurrency/blob/1734c0a7a2fe779390941a3bfe90e33efc698dfa/src/main.rs

TL;DR: instead of: Scope::scope_and_block(|s| { ... do:

Scope::scope_and_block(|s: &mut async_scoped::Scope<'_, (), async_scoped::spawner::use_async_std::AsyncStd>| { ...

This does require a change to async-scoped source code though, to make spawner public. Specifically, in async-scoped/src/lib.rs, change mod spawner; to pub mod spawner;.

rmanoka commented 2 years ago

The inference failure is intended as Scope is the general structure that supports both async-std and tokio. To use async-std, make sure you have enabled the use-async-std feature of the crate, and use AsyncScope instead of Scope. Pls. refer example in the docs: https://docs.rs/async-scoped/latest/async_scoped/#scope-api

Verdagon commented 2 years ago

That solved it! I'm not sure how I missed that, it felt like I'd tried everything at the time.

Thank you for your help!