Home > Blockchain >  Recursive async functions calling each other: cycle detected
Recursive async functions calling each other: cycle detected

Time:12-16

The following code is the simplified version of the code I'm trying to write.

Coming from Go I'm finding it a bit difficult to deal with recursive functions calling each other.

First try (REPL on Playground here):

#[derive(Debug)]
struct Team {
    id: String
}

impl Team {
    pub async fn query(with_coach: bool) -> Result<Option<Team>, ()> {
        if with_coach {
            let coach = Coach::query(false).await?;
            
            dbg!(coach);
        }

        Ok(None)
    }
}

#[derive(Debug)]
struct Coach {
    id: String
}

impl Coach {
    pub async fn query(with_team: bool) -> Result<Option<Coach>, ()> {
        if with_team {
            let team = Team::query(false).await?;
            
            dbg!(team);
        }
        
        Ok(None)
    }
}

#[tokio::main]
async fn main() {
    let team = Team::query(true).await;

    dbg!(team);
}

the error is:

error[E0733]: recursion in an `async fn` requires boxing
 --> src/main.rs:7:45
  |
7 |     pub async fn query(with_coach: bool) -> Result<Option<Team>, ()> {
  |                                             ^^^^^^^^^^^^^^^^^^^^^^^^ recursive `async fn`
  |
  = note: a recursive `async fn` must be rewritten to return a boxed `dyn Future`
  = note: consider using the `async_recursion` crate: https://crates.io/crates/async_recursion

error[E0733]: recursion in an `async fn` requires boxing
  --> src/main.rs:24:44
   |
24 |     pub async fn query(with_team: bool) -> Result<Option<Coach>, ()> {
   |                                            ^^^^^^^^^^^^^^^^^^^^^^^^^ recursive `async fn`
   |
   = note: a recursive `async fn` must be rewritten to return a boxed `dyn Future`
   = note: consider using the `async_recursion` crate: https://crates.io/crates/async_recursion

So I tried this second version (REPL on Playground here):

use std::{future::Future, pin::Pin};

#[derive(Debug)]
struct Team {
    id: String,
}

impl Team {
    pub async fn query<'a>(
        id: &'a str,
        with_coach: bool,
    ) -> Pin<Box<dyn Future<Output = Result<Option<Team>, ()>>   Send   'a>> {
        Box::pin(async move {
            if with_coach {
                let coach = Coach::query("", false).await.await?;

                dbg!(coach);
            }

            Ok(None)
        })
    }
}

#[derive(Debug)]
struct Coach {
    id: String,
}

impl Coach {
    pub async fn query<'a>(
        id: &'a str,
        with_team: bool,
    ) -> Pin<Box<dyn Future<Output = Result<Option<Coach>, ()>>   Send   'a>> {
        Box::pin(async move {
            if with_team {
                let team = Team::query("", false).await.await?;

                dbg!(team);
            }

            Ok(None)
        })
    }
}

#[tokio::main]
async fn main() {
    let team = Team::query("", true).await.await;

    dbg!(team);
}

but as you can imagine there is a (very strange) error:

error[E0391]: cycle detected when computing type of `<impl at src/main.rs:8:1: 8:10>::query::{opaque#0}`
  --> src/main.rs:12:10
   |
12 |     ) -> Pin<Box<dyn Future<Output = Result<Option<Team>, ()>>   Send   'a>> {
   |          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
note: ...which requires borrow-checking `<impl at src/main.rs:8:1: 8:10>::query`...
  --> src/main.rs:9:5
   |
9  | /     pub async fn query<'a>(
10 | |         id: &'a str,
11 | |         with_coach: bool,
12 | |     ) -> Pin<Box<dyn Future<Output = Result<Option<Team>, ()>>   Send   'a>> {
   | |____________________________________________________________________________^
note: ...which requires processing `<impl at src/main.rs:8:1: 8:10>::query`...
  --> src/main.rs:9:5
   |
9  | /     pub async fn query<'a>(
10 | |         id: &'a str,
11 | |         with_coach: bool,
12 | |     ) -> Pin<Box<dyn Future<Output = Result<Option<Team>, ()>>   Send   'a>> {
   | |____________________________________________________________________________^
note: ...which requires processing MIR for `<impl at src/main.rs:8:1: 8:10>::query`...
  --> src/main.rs:9:5
   |
9  | /     pub async fn query<'a>(
10 | |         id: &'a str,
11 | |         with_coach: bool,
12 | |     ) -> Pin<Box<dyn Future<Output = Result<Option<Team>, ()>>   Send   'a>> {
   | |____________________________________________________________________________^
note: ...which requires unsafety-checking `<impl at src/main.rs:8:1: 8:10>::query`...
  --> src/main.rs:9:5
   |
9  | /     pub async fn query<'a>(
10 | |         id: &'a str,
11 | |         with_coach: bool,
12 | |     ) -> Pin<Box<dyn Future<Output = Result<Option<Team>, ()>>   Send   'a>> {
   | |____________________________________________________________________________^
note: ...which requires building MIR for `<impl at src/main.rs:8:1: 8:10>::query`...
  --> src/main.rs:9:5
   |
9  | /     pub async fn query<'a>(
10 | |         id: &'a str,
11 | |         with_coach: bool,
12 | |     ) -> Pin<Box<dyn Future<Output = Result<Option<Team>, ()>>   Send   'a>> {
   | |____________________________________________________________________________^
note: ...which requires building THIR for `<impl at src/main.rs:8:1: 8:10>::query`...
  --> src/main.rs:9:5
   |
9  | /     pub async fn query<'a>(
10 | |         id: &'a str,
11 | |         with_coach: bool,
12 | |     ) -> Pin<Box<dyn Future<Output = Result<Option<Team>, ()>>   Send   'a>> {
   | |____________________________________________________________________________^
note: ...which requires type-checking `<impl at src/main.rs:8:1: 8:10>::query`...
  --> src/main.rs:13:9
   |
13 | /         Box::pin(async move {
14 | |             if with_coach {
15 | |                 let coach = Coach::query("", false).await.await?;
16 | |
...  |
20 | |             Ok(None)
21 | |         })
   | |__________^
   = note: ...which requires evaluating trait selection obligation `for<'r, 's, 't0> {core::future::ResumeTy, bool, &'r str, impl for<'s> core::future::future::Future<Output = core::pin::Pin<alloc::boxed::Box<(dyn core::future::future::Future<Output = core::result::Result<core::option::Option<Coach>, ()>>   core::marker::Send   's)>>>, (), core::pin::Pin<alloc::boxed::Box<(dyn core::future::future::Future<Output = core::result::Result<core::option::Option<Coach>, ()>>   core::marker::Send   't0)>>}: core::marker::Send`...
note: ...which requires computing type of `<impl at src/main.rs:30:1: 30:11>::query::{opaque#0}`...
  --> src/main.rs:34:10
   |
34 |     ) -> Pin<Box<dyn Future<Output = Result<Option<Coach>, ()>>   Send   'a>> {
   |          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
note: ...which requires borrow-checking `<impl at src/main.rs:30:1: 30:11>::query`...
  --> src/main.rs:31:5
   |
31 | /     pub async fn query<'a>(
32 | |         id: &'a str,
33 | |         with_team: bool,
34 | |     ) -> Pin<Box<dyn Future<Output = Result<Option<Coach>, ()>>   Send   'a>> {
   | |_____________________________________________________________________________^
note: ...which requires processing `<impl at src/main.rs:30:1: 30:11>::query`...
  --> src/main.rs:31:5
   |
31 | /     pub async fn query<'a>(
32 | |         id: &'a str,
33 | |         with_team: bool,
34 | |     ) -> Pin<Box<dyn Future<Output = Result<Option<Coach>, ()>>   Send   'a>> {
   | |_____________________________________________________________________________^
note: ...which requires processing MIR for `<impl at src/main.rs:30:1: 30:11>::query`...
  --> src/main.rs:31:5
   |
31 | /     pub async fn query<'a>(
32 | |         id: &'a str,
33 | |         with_team: bool,
34 | |     ) -> Pin<Box<dyn Future<Output = Result<Option<Coach>, ()>>   Send   'a>> {
   | |_____________________________________________________________________________^
note: ...which requires unsafety-checking `<impl at src/main.rs:30:1: 30:11>::query`...
  --> src/main.rs:31:5
   |
31 | /     pub async fn query<'a>(
32 | |         id: &'a str,
33 | |         with_team: bool,
34 | |     ) -> Pin<Box<dyn Future<Output = Result<Option<Coach>, ()>>   Send   'a>> {
   | |_____________________________________________________________________________^
note: ...which requires building MIR for `<impl at src/main.rs:30:1: 30:11>::query`...
  --> src/main.rs:31:5
   |
31 | /     pub async fn query<'a>(
32 | |         id: &'a str,
33 | |         with_team: bool,
34 | |     ) -> Pin<Box<dyn Future<Output = Result<Option<Coach>, ()>>   Send   'a>> {
   | |_____________________________________________________________________________^
note: ...which requires building THIR for `<impl at src/main.rs:30:1: 30:11>::query`...
  --> src/main.rs:31:5
   |
31 | /     pub async fn query<'a>(
32 | |         id: &'a str,
33 | |         with_team: bool,
34 | |     ) -> Pin<Box<dyn Future<Output = Result<Option<Coach>, ()>>   Send   'a>> {
   | |_____________________________________________________________________________^
note: ...which requires type-checking `<impl at src/main.rs:30:1: 30:11>::query`...
  --> src/main.rs:35:9
   |
35 | /         Box::pin(async move {
36 | |             if with_team {
37 | |                 let team = Team::query("", false).await.await?;
38 | |
...  |
42 | |             Ok(None)
43 | |         })
   | |__________^
   = note: ...which requires evaluating trait selection obligation `for<'r, 's, 't0> {core::future::ResumeTy, bool, &'r str, impl for<'s> core::future::future::Future<Output = core::pin::Pin<alloc::boxed::Box<(dyn core::future::future::Future<Output = core::result::Result<core::option::Option<Team>, ()>>   core::marker::Send   's)>>>, (), core::pin::Pin<alloc::boxed::Box<(dyn core::future::future::Future<Output = core::result::Result<core::option::Option<Team>, ()>>   core::marker::Send   't0)>>}: core::marker::Send`...
   = note: ...which again requires computing type of `<impl at src/main.rs:8:1: 8:10>::query::{opaque#0}`, completing the cycle
note: cycle used when checking item types in top-level module
  --> src/main.rs:1:1
   |
1  | / use std::{future::Future, pin::Pin};
2  | |
3  | | #[derive(Debug)]
4  | | struct Team {
...  |
51 | |     dbg!(team);
52 | | }
   | |_^

error[E0391]: cycle detected when computing type of `<impl at src/main.rs:8:1: 8:10>::query::{opaque#0}`
  --> src/main.rs:12:10
   |
12 |     ) -> Pin<Box<dyn Future<Output = Result<Option<Team>, ()>>   Send   'a>> {
   |          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
note: ...which requires borrow-checking `<impl at src/main.rs:8:1: 8:10>::query`...
  --> src/main.rs:9:5
   |
9  | /     pub async fn query<'a>(
10 | |         id: &'a str,
11 | |         with_coach: bool,
12 | |     ) -> Pin<Box<dyn Future<Output = Result<Option<Team>, ()>>   Send   'a>> {
   | |____________________________________________________________________________^
note: ...which requires processing `<impl at src/main.rs:8:1: 8:10>::query`...
  --> src/main.rs:9:5
   |
9  | /     pub async fn query<'a>(
10 | |         id: &'a str,
11 | |         with_coach: bool,
12 | |     ) -> Pin<Box<dyn Future<Output = Result<Option<Team>, ()>>   Send   'a>> {
   | |____________________________________________________________________________^
note: ...which requires processing MIR for `<impl at src/main.rs:8:1: 8:10>::query`...
  --> src/main.rs:9:5
   |
9  | /     pub async fn query<'a>(
10 | |         id: &'a str,
11 | |         with_coach: bool,
12 | |     ) -> Pin<Box<dyn Future<Output = Result<Option<Team>, ()>>   Send   'a>> {
   | |____________________________________________________________________________^
note: ...which requires unsafety-checking `<impl at src/main.rs:8:1: 8:10>::query`...
  --> src/main.rs:9:5
   |
9  | /     pub async fn query<'a>(
10 | |         id: &'a str,
11 | |         with_coach: bool,
12 | |     ) -> Pin<Box<dyn Future<Output = Result<Option<Team>, ()>>   Send   'a>> {
   | |____________________________________________________________________________^
note: ...which requires building MIR for `<impl at src/main.rs:8:1: 8:10>::query`...
  --> src/main.rs:9:5
   |
9  | /     pub async fn query<'a>(
10 | |         id: &'a str,
11 | |         with_coach: bool,
12 | |     ) -> Pin<Box<dyn Future<Output = Result<Option<Team>, ()>>   Send   'a>> {
   | |____________________________________________________________________________^
note: ...which requires building THIR for `<impl at src/main.rs:8:1: 8:10>::query`...
  --> src/main.rs:9:5
   |
9  | /     pub async fn query<'a>(
10 | |         id: &'a str,
11 | |         with_coach: bool,
12 | |     ) -> Pin<Box<dyn Future<Output = Result<Option<Team>, ()>>   Send   'a>> {
   | |____________________________________________________________________________^
note: ...which requires type-checking `<impl at src/main.rs:8:1: 8:10>::query`...
  --> src/main.rs:13:9
   |
13 | /         Box::pin(async move {
14 | |             if with_coach {
15 | |                 let coach = Coach::query("", false).await.await?;
16 | |
...  |
20 | |             Ok(None)
21 | |         })
   | |__________^
   = note: ...which requires evaluating trait selection obligation `for<'r, 's, 't0> {core::future::ResumeTy, bool, &'r str, impl for<'s> core::future::future::Future<Output = core::pin::Pin<alloc::boxed::Box<(dyn core::future::future::Future<Output = core::result::Result<core::option::Option<Coach>, ()>>   core::marker::Send   's)>>>, (), core::pin::Pin<alloc::boxed::Box<(dyn core::future::future::Future<Output = core::result::Result<core::option::Option<Coach>, ()>>   core::marker::Send   't0)>>}: core::marker::Send`...
note: ...which requires computing type of `<impl at src/main.rs:30:1: 30:11>::query::{opaque#0}`...
  --> src/main.rs:34:10
   |
34 |     ) -> Pin<Box<dyn Future<Output = Result<Option<Coach>, ()>>   Send   'a>> {
   |          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
note: ...which requires borrow-checking `<impl at src/main.rs:30:1: 30:11>::query`...
  --> src/main.rs:31:5
   |
31 | /     pub async fn query<'a>(
32 | |         id: &'a str,
33 | |         with_team: bool,
34 | |     ) -> Pin<Box<dyn Future<Output = Result<Option<Coach>, ()>>   Send   'a>> {
   | |_____________________________________________________________________________^
note: ...which requires processing `<impl at src/main.rs:30:1: 30:11>::query`...
  --> src/main.rs:31:5
   |
31 | /     pub async fn query<'a>(
32 | |         id: &'a str,
33 | |         with_team: bool,
34 | |     ) -> Pin<Box<dyn Future<Output = Result<Option<Coach>, ()>>   Send   'a>> {
   | |_____________________________________________________________________________^
note: ...which requires processing MIR for `<impl at src/main.rs:30:1: 30:11>::query`...
  --> src/main.rs:31:5
   |
31 | /     pub async fn query<'a>(
32 | |         id: &'a str,
33 | |         with_team: bool,
34 | |     ) -> Pin<Box<dyn Future<Output = Result<Option<Coach>, ()>>   Send   'a>> {
   | |_____________________________________________________________________________^
note: ...which requires unsafety-checking `<impl at src/main.rs:30:1: 30:11>::query`...
  --> src/main.rs:31:5
   |
31 | /     pub async fn query<'a>(
32 | |         id: &'a str,
33 | |         with_team: bool,
34 | |     ) -> Pin<Box<dyn Future<Output = Result<Option<Coach>, ()>>   Send   'a>> {
   | |_____________________________________________________________________________^
note: ...which requires building MIR for `<impl at src/main.rs:30:1: 30:11>::query`...
  --> src/main.rs:31:5
   |
31 | /     pub async fn query<'a>(
32 | |         id: &'a str,
33 | |         with_team: bool,
34 | |     ) -> Pin<Box<dyn Future<Output = Result<Option<Coach>, ()>>   Send   'a>> {
   | |_____________________________________________________________________________^
note: ...which requires building THIR for `<impl at src/main.rs:30:1: 30:11>::query`...
  --> src/main.rs:31:5
   |
31 | /     pub async fn query<'a>(
32 | |         id: &'a str,
33 | |         with_team: bool,
34 | |     ) -> Pin<Box<dyn Future<Output = Result<Option<Coach>, ()>>   Send   'a>> {
   | |_____________________________________________________________________________^
note: ...which requires type-checking `<impl at src/main.rs:30:1: 30:11>::query`...
  --> src/main.rs:31:5
   |
31 | /     pub async fn query<'a>(
32 | |         id: &'a str,
33 | |         with_team: bool,
34 | |     ) -> Pin<Box<dyn Future<Output = Result<Option<Coach>, ()>>   Send   'a>> {
   | |_____________________________________________________________________________^
   = note: ...which again requires computing type of `<impl at src/main.rs:8:1: 8:10>::query::{opaque#0}`, completing the cycle
note: cycle used when checking item types in top-level module
  --> src/main.rs:1:1
   |
1  | / use std::{future::Future, pin::Pin};
2  | |
3  | | #[derive(Debug)]
4  | | struct Team {
...  |
51 | |     dbg!(team);
52 | | }
   | |_^

What all this mean?

How can I fix this code?

CodePudding user response:

You were very close. You just don't need async when you return boxed future. More details here and here

Async fn creates a state machine type containing each sub-Future being .awaited. For recursive async functions the resulting state machine type has to contain itself so you get infinitely-sized type. So you have to Box it.

However compiler restrictions won't allow just boxing at the moment. You have to make recursive function into a non-async function which returns a boxed async block.

This compiles and runs:

use std::{future::Future, pin::Pin};

#[derive(Debug)]
struct Team {
    id: String,
}

impl Team {
    pub fn query<'a>(
        id: &'a str,
        with_coach: bool,
    ) -> Pin<Box<dyn Future<Output = Result<Option<Team>, ()>>   Send   'a>> {
        Box::pin(async move {
            if with_coach {
                let coach = Coach::query("", false).await?;

                dbg!(coach);
            }

            Ok(None)
        })
    }
}

#[derive(Debug)]
struct Coach {
    id: String,
}

impl Coach {
    pub fn query<'a>(
        id: &'a str,
        with_team: bool,
    ) -> Pin<Box<dyn Future<Output = Result<Option<Coach>, ()>>   Send   'a>> {
        Box::pin(async move {
            if with_team {
                let team = Team::query("", false).await?;

                dbg!(team);
            }

            Ok(None)
        })
    }
}

#[tokio::main]
async fn main() {
    let team = Team::query("", true).await;

    dbg!(team);
}
  • Related