rust-lang / rust-lang/rust-clippy

`clippy::write_literal` should suggest using `write_str` for `fmt::Write`

Open
#13,449 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

C-enhancement S-blocked
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

Summary

The clippy::write_literal lint suggests changing code like write!(f, "{}", "{}") to write!(f, "{{}}"), but this can require a lot of changes to the string if it contains many { or } chars. If the first argument to write! implements fmt::Write, clippy should suggest changing it to f.write_str("{}") instead.

Reproducer

I tried this code:

use std::fmt::Write;
fn main() {
    let mut s = String::new();
    write!(s, "{}", "{}").unwrap();
}

I expected to see this happen:

warning: literal with an empty format string
 --> clippy-write-literal.rs:4:21
  |
4 |     write!(s, "{}", "{}").unwrap();
  |                     ^^^^
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#write_literal
  = note: `#[warn(clippy::write_literal)]` on by default
help: try
  |
4 -     write!(s, "{}", "{}").unwrap();
4 +     s.write_str("{}").unwrap();
  |

warning: 1 warning emitted

Instead, this happened:

warning: literal with an empty format string
 --> clippy-write-literal.rs:4:21
  |
4 |     write!(s, "{}", "{}").unwrap();
  |                     ^^^^
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#write_literal
  = note: `#[warn(clippy::write_literal)]` on by default
help: try
  |
4 -     write!(s, "{}", "{}").unwrap();
4 +     write!(s, "{{}}").unwrap();
  |

warning: 1 warning emitted
Version

rustc 1.81.0 (eeb90cda1 2024-09-04)
binary: rustc
commit-hash: eeb90cda1969383f56a2637cbd3037bdf598841c
commit-date: 2024-09-04
host: aarch64-apple-darwin
release: 1.81.0
LLVM version: 18.1.7

Additional Labels

No response

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by locating the write_literal lint and its handling of fmt::Write targets. Use the reproducer to compare the current suggestion with the requested s.write_str("{}").unwrap() form, then verify that the diagnostic changes while other write_literal cases remain correct.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.