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?