Skip to content

Improvement to write! macro with wrong type for string literal argument #86865

Closed
@insanitybit

Description

@insanitybit

Given the following code:
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=4c5ff2fc026afd1a666633cba4c31865

pub fn example(f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    write!(f, b"Foo{}", "bar")
}

The current output is:

error: format argument must be a string literal
 --> src/lib.rs:4:15
   |
4 |     write!(f, b"Foo{}", "bar")
   |               ^^^^^^^^
   |
help: you might be missing a string literal to format with
   |
4 |     write!(f, "{} {}", b"Foo{}", "bar")

Ideally the output should look like:

 error: format argument must be a string literal, **found byte literal**
  --> src/lib.rs:4:15
   |
 4 |     write!(f, b"Foo{}", "bar")
   |               ^^^^^^^^
   |
 help: you might be missing a string literal to format with
   |
4 |     write!(f, "{} {}", b"Foo{}", "bar")
 help: you may have meant to pass in a string literal instead of a byte literal
   |
 4 |     write!(f, b"Foo{}", "bar")
  |               ^ try removing this 'b'
4 |     write!(f, "Foo{}", "bar")

So this is super trivial, but I just ran into this and I haven't used write! in a while so I sorta did a double take and it took me a second to figure out why it was suggesting what it was suggesting.

I was just refactoring some code that had used a byte literal beforehand. Two things would help:

  1. Telling me that I passed in a byte literal where a string literal was expected (or whatever else - right now it only says what's expected, not what was provided). IMO this alone would have been a big help and I would have spent 0 cycles thinking about what the problem could be.

  2. Since this is, to a human, clearly a case where I intended the byte literal to be the format string, in an ideal world that would be pointed out to me. I realize that this is open to interpretation - is it "clearly" the case because it's a byte literal? Or a byte literal with {}? IDK! Food for thought.

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