Skip to content

Rust diagnostic for impl Trait suggests broken code #97760

Closed
@jonasbb

Description

@jonasbb

Given the following code:
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=87a0987f6c8b7b1a67b03338e2a4ed09
The issues also reproduces with the nightly version on the playground.

pub fn print_values(values: &impl IntoIterator)
where
{
    for x in values.into_iter() {
        println!("{x}");
    }
}

The current output is:

error[[E0277]](https://doc.rust-lang.org/stable/error-index.html#E0277): `<impl IntoIterator as IntoIterator>::Item` doesn't implement `std::fmt::Display`
 --> src/lib.rs:5:20
  |
5 |         println!("{x}");
  |                    ^ `<impl IntoIterator as IntoIterator>::Item` cannot be formatted with the default formatter
  |
  = help: the trait `std::fmt::Display` is not implemented for `<impl IntoIterator as IntoIterator>::Item`
  = 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` (in Nightly builds, run with -Z macro-backtrace for more info)
help: introduce a type parameter with a trait bound instead of using `impl Trait`
  |
1 ~ pub fn print_values<I: IntoIterator>(values: &impl IntoIterator)
2 ~ where where <I as IntoIterator>::Item: std::fmt::Display
  |

The proposed code has multiple problems.
The code doubles the where leading to broken Rust.
The diagnostic correctly introduces the I: IntoIterator, but does not replace the impl IntoIterator in the function arguments.

If you remove the where from the initial example, the diagnostic changes to include +++ markers for the added code. These seem helpful and to me it is not clear why they are missing initially.

help: introduce a type parameter with a trait bound instead of using `impl Trait`
  |
1 | pub fn print_values<I: IntoIterator>(values: &impl IntoIterator) where <I as IntoIterator>::Item: std::fmt::Display
  |                    +++++++++++++++++                             ++++++++++++++++++++++++++++++++++++++++++++++++++

Metadata

Metadata

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions