Skip to content

Type confusion when interacting with HashMap both via Borrow and directly #141008

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
bertptrs opened this issue May 14, 2025 · 2 comments
Closed
Labels
C-bug Category: This is a bug.

Comments

@bertptrs
Copy link
Contributor

bertptrs commented May 14, 2025

I tried this code, simplified from the larger example.

use std::collections::HashMap;
use std::borrow::Borrow;
use std::hash::Hash;

pub struct MyStruct<K>(HashMap<K, Vec<K>>);

impl<K> MyStruct<K>
where K: Hash + Eq
{
    pub fn remove<Q>(&mut self, key: &Q)
    where
        Q: Hash + Eq + ?Sized,
        K: Borrow<Q>
    {
        if let Some(val) = self.0.remove(key) {
            for v in val {
                self.0.get_mut(&v).unwrap().clear();
                // works: self.0.get_mut::<K>(&v).unwrap().clear();
            }
        }
    }
}

I expected to see this happen: it compiles successfully.

Instead, this happened: It complains that the argument to get_mut is of type &K rather than the expected type &Q. While this is true, it's irrelevant, as &K is a valid argument to that function. This can be shown by turbofishing the call.

Meta

rustc --version --verbose:

rustc 1.86.0 (05f9846f8 2025-03-31) (Arch Linux rust 1:1.86.0-1)
binary: rustc
commit-hash: 05f9846f893b09a1be1fc8560e33fc3c815cfecb
commit-date: 2025-03-31
host: x86_64-unknown-linux-gnu
release: 1.86.0
LLVM version: 19.1.7

Also verified with nightly via the playground.

Backtrace

<backtrace>

@bertptrs bertptrs added the C-bug Category: This is a bug. label May 14, 2025
@rustbot rustbot added the needs-triage This issue may need triage. Remove it if it has been sufficiently triaged. label May 14, 2025
@hanna-kruppe
Copy link
Contributor

I believe this is another instance of #24066 - while inferring the type parameter for the get_mut call, the compiler latches onto the superficially relevant K: Borrow<Q> bound from the where clause.

@jieyouxu
Copy link
Member

Indeed, seems like it.

@jieyouxu jieyouxu removed the needs-triage This issue may need triage. Remove it if it has been sufficiently triaged. label May 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
C-bug Category: This is a bug.
Projects
None yet
Development

No branches or pull requests

4 participants