Skip to content

Explicitly stated argument-type of a closure gets overwritten by its type alias #100800

Closed
@BattyBoopers

Description

@BattyBoopers

I tried this code:

#![feature(type_alias_impl_trait,)]

trait Anything {}
impl<T> Anything for T {}
type Input = impl Anything;
fn run<F: FnOnce(Input) -> ()>(f: F, i: Input) {
    f(i);
}

fn main() {
    run(|x: u32| {println!("{x}");}, 0);
}

The type of the closure's argument is explicitly stated and not inferred. Therefore, the closure-body should be aware of the type of its argument as it was stated (u32) and the code should compile correctly.

Instead, this code behaves as if the type was inferred to be its type alias (Input). This hides the Display implementation of u32 and results in an error:

error[E0277]: `Input` doesn't implement `std::fmt::Display`
  --> src/main.rs:11:30
   |
11 |     run(|x: u32| {println!("{x}");}, 0);
   |                              ^ `Input` cannot be formatted with the default formatter
   |
   = help: the trait `std::fmt::Display` is not implemented for `Input`
   = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
   = note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)

Another way to look at this is that if

|x: u32| {println!("{x}");}

is valid on its own without requiring the inferring of any types, then doing

run(|x: u32| {println!("{x}");}, 0);

should not cause any changes in semantics inside the closure-body.

Meta

rustc --version --verbose:

rustc 1.65.0-nightly (0b79f758c 2022-08-18)
binary: rustc
commit-hash: 0b79f758c9aa6646606662a6d623a0752286cd17
commit-date: 2022-08-18
host: x86_64-unknown-linux-gnu
release: 1.65.0-nightly
LLVM version: 15.0.0

Metadata

Metadata

Assignees

Labels

A-closuresArea: Closures (`|…| { … }`)C-bugCategory: This is a bug.F-type_alias_impl_trait`#[feature(type_alias_impl_trait)]`requires-nightlyThis issue requires a nightly compiler in some way.

Type

No type

Projects

Status

Done

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions