Skip to content

Assignment inside format_args! is ignored #45256

Closed
@nikolads

Description

@nikolads

Assignments inside format_args! are ignored. Instead only the right-hand side of the expression is used.

I tried this code:

fn main() {
    let mut x = 1;
    println!("first: {}", x = 3);
    println!("second: {}", x);
}

or a similar one, using directly format_args:

use std::io::{self, Write};

fn main() {
    let mut x = 1; 
    io::stdout().write_fmt(format_args!("first: {}\n", x = 3));
    io::stdout().write_fmt(format_args!("second: {}\n", x));
}

I expected to see this:

first: ()
second: 3

Instead the output was:

first: 3
second: 1

It looks like the the assignment x = 3 is ignored and is instead treated as if it was just 3.
I could only replicate this with format_args! and macros that use it. Other macros, like assert_eq!, work as expected.

Meta

rustc --version --verbose:

rustc 1.22.0-nightly (dcbbfb6e8 2017-10-12)
binary: rustc
commit-hash: dcbbfb6e807fdff9c9ba80073bb755f9d9d95e31
commit-date: 2017-10-12
host: x86_64-unknown-linux-gnu
release: 1.22.0-nightly
LLVM version: 4.0

(also tried on rustc 1.20.0-stable and rustc 1.21.0-stable)

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-lintsArea: Lints (warnings about flaws in source code) such as unused_mut.C-bugCategory: This is a bug.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