How to make function parameters support both value types and reference types

I have a hash map of type Map<K, V> with an entry(k) function whose signature is:

    pub fn entry<Q: Eq + Hash + ?Sized>(&self, key: &Q)
    where
        K: Borrow<Q> + for<'c> From<&'c Q>,

Using reference types helps avoid unnecessary clones by only calling K::from(key) when needed. However, this approach doesn't support value types like u32. Is there a way to make it work with both value types and reference types?

I think this does what you want.

    pub fn entry<Q>(&self, key: &Q)
    where
        Q: Eq + Hash + ?Sized + ToOwned<Owned = K>,
        // Technically implied by the above but you need this to avoid
        // breaking inference
        K: Borrow<Q>,

Yeah, I have tried this approach, but it does not solve all my problems. For example, my key type is CustomBytes, and the parameter type passed in is &[u8].

1 Like