Skip to content

Suggest examples of format specifiers in error messages #68293

@sunjay

Description

@sunjay

This is real code that someone I am helping learn Rust wrote today. It's a problem you could easily stare at for hours and never figure it out. Especially if you're new to using format strings. The code actually looks correct (from a distance).

fn main() {
    println!(":#?", vec![123]);
}

Here's the error message we produce:

error: argument never used
 --> src/main.rs:2:21
  |
2 |     println!(":#?", vec![123]);
  |              -----  ^^^^^^^^^ argument never used
  |              |
  |              formatting specifier missing

The person I was helping assumed that some formatting trait hadn't been implemented. It didn't occur to them that the format specifier was incorrect even though it said "formatting specifier missing".

I think we could help them by adding a hint or something that shows an example of a specifier whenever we say "formatting specifier missing".

Something like:

hint: format specifiers usually look like `{}` or `{:?}`

This would then help them compare against what they have and find the problem sooner.

From @estebank: (source)

We already handle C-style formatting strings and provide an appropriate suggestion, so I think this would also be reasonable to handle this.

fn main() {
    println!("%d", 42);
}

Adding logic to here should be relatively straightforward.

Also, this case should also be slightly tweaked to point at the formatting
specifiers that were found:

fn main() {
    println!("{} :#?", 1, 42);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`C-enhancementCategory: An issue proposing an enhancement or a PR with one.T-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