Skip to content

async closure parameter type inference does not work anymore #127425

Closed
@peku33

Description

@peku33

When using async closures, rust since around 1.80 fails to infer parameter type in most scenarios.

#![feature(async_closure)]

use anyhow::Error;
use futures::{stream::repeat_with, StreamExt};

fn accept_str(_: &str) {}
fn accept_string(_: &String) {}

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Error> {
    // when using closure returning async block - everything works
    repeat_with(|| "foo".to_owned())
        .take(1)
        .for_each(|value| async move {
            accept_str(&value); // ok
            accept_str(value.as_str()); // ok
            accept_string(&value); // ok
        })
        .await;

    // when using async closure, most options fail
    repeat_with(|| "foo".to_owned())
        .take(1)
        .for_each(async move |value| {
            // error on whole closure, rust thinks that type of value is `str`
            // accept_str(&value);

            // type annotations needed, cannot infer type
            // accept_str(value.as_str());

            // this works
            accept_string(&value); // ok
        })
        .await;

    // can be fixed by providing type hint on async closure parameter
    repeat_with(|| "foo".to_owned())
        .take(1)
        .for_each(async move |value: String| {
            accept_str(&value); // ok
            accept_str(value.as_str()); // ok
            accept_string(&value); // ok
        })
        .await;

    Ok(())
}

I expected to see this happen: All options used to work in past versions of rust

Instead, this happened: Without explicit type hint it fails

Version it worked on

It used to work in the past, around 1.79

Version with regression

rustc 1.81.0-nightly (524d806c6 2024-07-05)
binary: rustc
commit-hash: 524d806c62a82ecc0cf8634b94997ae506f4d6f9
commit-date: 2024-07-05
host: x86_64-pc-windows-msvc
release: 1.81.0-nightly
LLVM version: 18.1.7

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions