Skip to content

Invalid format string with certain fill characters yields incorrect suggestion #139104

Closed
@jdahlstrom

Description

@jdahlstrom

The following line that's missing an alignment specifier between the (intended) fill character _ and width+precision 1.4:

println!("{foo:_1.4}", foo = 3.14);

makes the compiler think we're trying to access a tuple field and helpfully but incorrectly suggests replacing it with

println!("{0}", foo:_1.4, foo = 3.14);

which is, of course, invalid syntax. The same holds for any alphabetic character as well as ..

Current output

error: invalid format string: tuple index access isn't supported
 --> src/main.rs:4:16
  |
4 |     println!("{foo:_1.4}", foo = 3.14);
  |                ^^^^^^^^ not supported in format string
  |
help: consider using a positional formatting argument instead
  |
4 |     println!("{0}", foo:_1.4, foo = 3.14);
  |                ~  ++++++++++

Desired output

error: invalid format string: invalid alignment specifier
 --> src/main.rs:4:16
  |
4 |     println!("{foo:_1.4}", foo = 3.14);
  |                    ^ not supported in format string
  |
help: if you're trying to use a fill character, it must be followed by one of `<` `>` `^`
  |
4 |     println!("{foo:_>1.4}", foo = 3.14);
  |                     +

Other cases

Using a non-alphanumeric fill character that's not [._+-] yields a different error message that is not incorrect but is perhaps not very helpful:

error: invalid format string: expected `}`, found `*`
 --> src/main.rs:4:20
  |
4 |     println!("{foo:*10.4}", foo = 3.14);
  |               -    ^ expected `}` in format string
  |               |
  |               because of this opening brace
  |
  = note: if you intended to print `{`, you can escape it using `{{`

Rust Version

rustc 1.85.1 (4eb161250 2025-03-15)
binary: rustc
commit-hash: 4eb161250e340c8f48f66e2b929ef4a5bed7c181
commit-date: 2025-03-15
host: x86_64-apple-darwin
release: 1.85.1
LLVM version: 19.1.7

Metadata

Metadata

Assignees

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