rust-lang / rust-lang/rust-clippy

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

Open
#13,403 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

I-suggestion-causes-error
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the example in src/bin/test.rs with cargo clippy and start by tracing the cmp_owned lint and its suggestion generation. Confirm that removing .to_string() changes the comparison result, then add a regression test showing the suggestion preserves semantics.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.