Skip to content

Erronous "unnecessary use of to_string" with colored::ColoredString #11102

Closed
@stevecheckoway

Description

@stevecheckoway

Summary

Clippy suggests replacing &foo.to_string() with &foo. When foo is a ColoredString from the popular colored crate, this suggestion is incorrect because &foo dereferences to just the underlying characters without including the terminal control characters for setting the colors.

Lint Name

clippy::unnecessary_to_owned

Reproducer

I tried this code:

use colored::{ColoredString, Colorize};

fn main() {
    let mut s = String::new();
    let c: ColoredString = "red".red();
    s.push_str(&c);
    s.push('\n');
    s.push_str(&c.to_string());
    println!("{s}");
}

I saw this happen:

Clippy warns on the s.push_str(&c.to_string()). The code prints red twice but only the second is colored red.

I expected to see this happen:

I expected no warning from clippy because the .to_string() is correct (and seems required).

Version

rustc 1.70.0 (90c541806 2023-05-31)
binary: rustc
commit-hash: 90c541806f23a127002de5b4038be731ba1458ca
commit-date: 2023-05-31
host: aarch64-apple-darwin
release: 1.70.0
LLVM version: 16.0.2

Additional Labels

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: Clippy is not doing the correct thingI-false-positiveIssue: The lint was triggered on code it shouldn't have

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions