rust-lang / rust-clippy

A bunch of lints to catch common mistakes and improve your Rust code. Book: https://doc.rust-lang.org/clippy/
https://rust-lang.github.io/rust-clippy/
Other
11.37k stars 1.53k forks source link

`#[warn(clippy::cmp_owned)]`: wrong suggestion to remove .to_string() #13403

Open dilyanpalauzov opened 1 month ago

dilyanpalauzov commented 1 month ago

Description

fn main() {
    if let Ok(serde_json::Value::Object(x)) = serde_json::from_str("{\"u\":\"\"}") {
        if x["u"].to_string() == "\"\"" {
            println!("A1");
        }
        if x["u"] == "\"\"" {
            println!("A2");
        }
    }
}

The above prints only A1 and does not emit A2. cargo clippy suggests

warning: this creates an owned instance just for comparison
 --> src/bin/test.rs:3:12
  |
3 |         if x["u"].to_string() == "\"\"" {
  |            ^^^^^^^^^^^^^^^^^^ help: try: `x["u"]`
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#cmp_owned
  = note: `#[warn(clippy::cmp_owned)]` on by default

When I replace x["u"].to_string() with x["u"], as clippy suggests, the code does not work any more.

Version

$ cargo clippy --version
clippy 0.1.81

$ rustc -Vv
rustc 1.81.0 (eeb90cda1 2024-09-04) (Fedora 1.81.0-1.fc40)
binary: rustc
commit-hash: eeb90cda1969383f56a2637cbd3037bdf598841c
commit-date: 2024-09-04
host: x86_64-unknown-linux-gnu
release: 1.81.0
LLVM version: 18.1.6

Additional Labels

No response

alex-semenyuk commented 1 month ago

@rustbot label I-suggestion-causes-error