rust-lang / rust-lang/rust

`format_args` deduplicates consts with interior mutability or destructor

Open
#145,739 21 comments 6 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-const-eval A-destructors A-fmt C-discussion I-lang-radar T-compiler T-lang
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

I'm not sure if this is a bug or not.

I tried this code:

use std::fmt::{self, Display, Formatter};
use std::cell::Cell;

struct PrintCounter(Cell<usize>);

impl Display for PrintCounter {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        let counter = 1 + self.0.get();
        self.0.set(counter);
        write!(f, "{counter}")
    }
}

const ZERO: PrintCounter = PrintCounter(Cell::new(0));

fn main() {
    println!("{ZERO}, {ZERO}");
}

I expected the code to print 1, 1, since I am creating two separate PrintCounter values and printing them separately.

Instead, it printed 1, 2. The compiler seemed to have deduplicated the two mentions of ZERO into one mention.

Note that if the code is modified to be println!("{}, {}", ZERO, ZERO);, then it correctly prints 1, 1.

@rustbot labels +A-fmt

Meta

Reproducible on the playground with version 1.91.0-nightly (2025-08-20 040a98af70f0a7da03f3)

Related

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 running the supplied Rust playground reproducer on the stated nightly version and compare it with the println!("{}, {}", ZERO, ZERO) form. Review related PR #149926, then trace the format_args handling of repeated const arguments. Done means the expected behavior is agreed and the discrepancy is fixed or documented with coverage for interior mutability and destructors.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.