Skip to content

Incorrect suggested removal of to_string on slice #9256

Closed
@RosieBaish

Description

@RosieBaish

Summary

clippy::to_string_in_format_args gives incorrect output when you call to_string on a str slice.
The code it suggests doesn't compile.

Reproducer

I tried this code:

fn print_substring(original: &str) {
    assert!(original.len() > 10);
    println!("{}", original[..10].to_string());
}

fn main() {
    print_substring("Hello, world!");
}

I expected to see this happen:
Clippy would either produce no error, or offer a valid correction

Instead, this happened:
It offered this alternative, which doesn't compile.
original[..10] doesn't have a known size, so can't be passed to println!
It should be &original[..10]

warning: `to_string` applied to a type that implements `Display` in `println!` args
 --> src/main.rs:3:34
  |
3 |     println!("{}", original[..10].to_string());
  |                                  ^^^^^^^^^^^^ help: remove this

Version

rustc 1.62.0 (a8314ef7d 2022-06-27)
binary: rustc
commit-hash: a8314ef7d0ec7b75c336af2c9857bfaf43002bfc
commit-date: 2022-06-27
host: x86_64-unknown-linux-gnu
release: 1.62.0
LLVM version: 14.0.5

Additional Labels

@rustbot label +I-suggestion-causes-error

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: Clippy is not doing the correct thingI-suggestion-causes-errorIssue: The suggestions provided by this Lint cause an ICE/error when applied

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions