Skip to content

unnecessary_to_owned false positive when keying HashSet<&String> #14833

Closed
@your-diary

Description

@your-diary

Summary

I tried this code:

use std::collections::HashSet;

fn main() {
    let mut s = HashSet::<&String>::new();
    let key = "hello".to_string();
    s.insert(&key);

    s.remove(&"hello".to_owned());
}

I saw this happen:

warning: unnecessary use of `to_owned`
 --> src/main.rs:8:14
  |
8 |     s.remove(&"hello".to_owned());
  |              ^^^^^^^^^^^^^^^^^^^ help: replace it with: `"hello"`
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_to_owned
  = note: `#[warn(clippy::unnecessary_to_owned)]` on by default

warning: `a` (bin "a") generated 1 warning
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.02s

However, when I fix the code as it tells me, compilation error occurs:

   Compiling a v0.1.0 (/Users/user/a)
error[E0277]: the trait bound `&String: Borrow<str>` is not satisfied
   --> src/main.rs:8:14
    |
8   |     s.remove("hello");
    |       ------ ^^^^^^^ the trait `Borrow<str>` is not implemented for `&String`
    |       |
    |       required by a bound introduced by this call
    |
    = help: the trait `Borrow<str>` is not implemented for `&String`
            but it is implemented for `String`
    = help: for that trait implementation, expected `String`, found `&String`
note: required by a bound in `HashSet::<T, S>::remove`
   --> /Users/user/.rustup/toolchains/stable-aarch64-apple-darwin/lib/rustlib/src/rust/library/std/src/collections/hash/set.rs:966:12
    |
964 |     pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
    |            ------ required by a bound in this associated function
965 |     where
966 |         T: Borrow<Q>,
    |            ^^^^^^^^^ required by this bound in `HashSet::<T, S>::remove`

For more information about this error, try `rustc --explain E0277`.
error: could not compile `a` (bin "a") due to 1 previous error

Lint Name

unnecessary_to_owned

Reproducer

No response

Version

rustc 1.86.0 (05f9846f8 2025-03-31)
binary: rustc
commit-hash: 05f9846f893b09a1be1fc8560e33fc3c815cfecb
commit-date: 2025-03-31
host: aarch64-apple-darwin
release: 1.86.0
LLVM version: 19.1.7

Additional Labels

No response

Metadata

Metadata

Assignees

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