【发布时间】:2015-09-04 15:39:33
【问题描述】:
我想插入到 HashMap 中,但要保留一个不可变的借用键以传递到位置。在我的情况下,键是字符串。
这是一种方式:
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));
但这需要克隆。
这个一直工作到 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));
如何使用 Rust 1.2.0 完成此任务?
理想情况下,我希望将一个键放入 HashMap 但保留对它的引用,并允许我使用 &str 类型访问其中的元素,而无需额外分配。
【问题讨论】:
标签: rust