Borrow trait and multiple borrows

I have struct as shown below and I can "borrow" it as the template parameter "K".


#[derive(Debug)]
pub (super) struct KeyValue<K, V>
    where K : Eq + Hash + Debug,
          V : Debug
{
    k : K,
    v : V
}

impl<K, V> Borrow<K> for KeyValue<K, V>
    where K : Eq + Hash + Debug,
          V : Debug,                    
{
    fn borrow(&self) -> &K
    {
        return &self.k_;
    }
}

However if the K is a String I would like to borrow it as a &str too. How can I accomplish that? I would like to do something as shown below. But this obviously doesn't compile. Any suggestions as to how this can be accomplished?


impl<K, V> Borrow<Q> for KeyValue<K, V>
    where K : Borrow<Q> + Eq + Hash + Debug,
          V : Debug,                    
{
    fn borrow(&self) -> &Q
    {
        return &self.k_.borrow();
    }
}

You can implement Borrow for any concrete K:

impl<V> Borrow<str> for KeyValue<String, V>
    where V: Debug,                    
{
    fn borrow(&self) -> &str {
        &self.k
    }
}
1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.