1

I have a HashMap<Node, u32> and I want to search is using a &str instead of a String; Is it possible somehow?

use std::collections::HashMap;

#[derive(PartialEq, Hash, Eq, Clone, Copy, Debug)]
enum NodeType {
    A,
    B,
}

#[derive(PartialEq, Hash, Eq, Clone, Debug)]
struct Node {
    id: String,
    code: u8,
    node_type: NodeType,
}

#[derive(PartialEq, Hash, Eq, Clone, Debug)]
struct NodeRef<'a> {
    id: &'a str,
    code: u8,
    node_type: NodeType,
}

fn main() {
    let m = HashMap::<Node, u32>::new();
    let x = NodeRef {
        id: "aaaa",
        code: 5,
        node_type: NodeType::A,
    };
    m.get(&x);
}

This code compiles if I add:

impl<'a> Borrow<NodeRef<'a>> for Node {
    fn borrow(&self) -> &NodeRef<'a> {
       unimplemented!();
    }
}

I have no idea how to implement borrow method:

impl<'a> Borrow<NodeRef<'a>> for Node {
    fn borrow(&self) -> &NodeRef<'a> {
        &NodeRef {
            id: self.id.as_str(),
            code: self.code,
            node_type: self.node_type,
        }
    }
}

This doesn't compile because of the reference to temporary variable. One way I see to use one global NodeRef per thread, are there any other ways?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
user1244932
  • 7,352
  • 5
  • 46
  • 103
  • Why don't you just use [`Cow`](https://doc.rust-lang.org/std/borrow/enum.Cow.html)? – Boiethios Aug 06 '18 at 11:43
  • 2
    A related question is [How to implement HashMap with two keys?](https://stackoverflow.com/questions/45786717/how-to-implement-hashmap-with-two-keys) – trent Aug 06 '18 at 11:58

0 Answers0