I want to insert into a HashMap but keep an immutable borrow of the key to pass around to places. In my case the keys are strings.
This is one way:
use std::collections::HashMap;
let mut map = HashMap::new();
let id = "data".to_string(); // This needs to be a String
let cloned = id.clone();
map.insert(id, 5);
let one = map.get(&cloned);
let two = map.get("data");
println!("{:?}", (one, two));
But this requires a clone.
This one worked until Rust 1.2.0:
use std::collections::HashMap;
use std::rc::Rc;
use std::string::as_string;
let mut map = HashMap::new();
let data = Rc::new("data".to_string()); // This needs to be a String
let copy = data.clone();
map.insert(data, 5);
let one = map.get(©);
let two = map.get(&*as_string("data"));
println!("{:?}", (one, two));
How can I accomplish this with Rust 1.2.0?
Ideally I would want to put a key into a HashMap but keep a reference to it, and allow me to access elements in it with &str
types, with no extra allocating.