Rust

Rust

Made by DeepSource

Found print! in implementation of Display RS-E1034

Bug risk
Major

The fmt method provided by the Display trait uses a formatter to generate the output string. It does not directly write to stdout or stderr. Using print! or eprint! in this implementation leads to incorrect functionality. Use only the write! macro to write the string into the formatter in the fmt implementation.

Bad practice

use std::fmt;

struct Foo { bar: usize }

impl fmt::Display for Foo {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        print!("This is bar in Foo: {}", self.bar)
    }
}

Recommended

use std::fmt;

struct Foo { bar: usize }

impl fmt::Display for Foo {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "This is bar in Foo: {}", self.bar)
    }
}