Skip to content

Poor error message when spawning a future returned by an async fn that takes an owned value as reference #81096

@LukeMathWalker

Description

@LukeMathWalker

Let's consider this snippet:

async fn test(a: &str) {
    println!("{}", a)
}

#[tokio::main]
async fn main() {
    let owned = "Hello!".to_string();
    tokio::spawn(test(&owned));
}

If we try to compile it, we'll get the following error:

error[E0597]: `owned` does not live long enough
 --> src/main.rs:8:23
  |
8 |     tokio::spawn(test(&owned));
  |                  -----^^^^^^-
  |                  |    |
  |                  |    borrowed value does not live long enough
  |                  argument requires that `owned` is borrowed for `'static`
9 | }
  | - `owned` dropped here while still borrowed

error: aborting due to previous error

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

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

The intent here is quite clear: I have ownership of owned, I want to pass it to test and then call tokio::spawn on the resulting future. The error message, though, does not point the user in the right direction.
The issue is indeed about lifetimes, but owned is never used again - therefore it'd make sense for the compiler to push the user into creating an async block that takes ownership of owned and gives back a 'static future. E.g.

async fn test(a: &str) {
    println!("{}", a)
}

#[tokio::main]
async fn main() {
    let owned = "Hello!".to_string();
    let fut = async move {
        test(&owned).await;
    };
    tokio::spawn(fut);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-async-awaitArea: Async & AwaitA-borrow-checkerArea: The borrow checkerA-diagnosticsArea: Messages for errors, warnings, and lintsA-lifetimesArea: Lifetimes / regionsAsyncAwait-TriagedAsync-await issues that have been triaged during a working group meeting.C-enhancementCategory: An issue proposing an enhancement or a PR with one.D-terseDiagnostics: An error or lint that doesn't give enough information about the problem at hand.S-has-mcveStatus: A Minimal Complete and Verifiable Example has been found for this issueT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions