rust 相互调用的递归异步函数:检测到循环

2ic8powd  于 2022-12-19  发布在  其他
关注(0)|答案(1)|浏览(108)

下面的代码是我尝试编写的代码的简化版本。
从Go语言学起,我发现处理递归函数之间的相互调用有点困难。
第一次尝试(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);
}

错误为:

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

所以我尝试了第二个版本(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);
}

但是你可以想象有一个(非常奇怪的)错误:

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 | | }
   | |_^

这一切意味着什么?
如何修复此代码?

doinxwow

doinxwow1#

你已经很接近了。当你返回boxed future时,你不需要异步。更多详细信息herehere
Async fn创建一个状态机类型,其中包含每个. awaited子Future。对于递归async函数,生成的状态机类型必须包含自身,以便获得无限大小的类型。因此必须对其进行装箱。
但是编译器的限制不允许只装箱,你必须把递归函数变成一个非异步函数,返回一个装箱的异步块。
这将编译并运行:

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);
}

相关问题