在 Rust 中,我有一个HashMap密钥是(String, String). 现在我有(&str, &str)数据了。有什么方法可以将其用作查询而不使用Strings 吗?
我相当确定这是不可能的。但是如果你可以改变,你可以通过使用: (playground)HashMap来获得你想要的行为Cow
// Make the map
let map: HashMap<(Cow<str>, Cow<str>), usize> = [
("a", "b"),
("c", "d"),
("e", "f"),
("g", "h"),
("i", "j"),
("k", "l"),
]
.into_iter()
.enumerate()
.map(|(n, (a, b))| {
// Create Cows with owned Strings
let a = Cow::Owned(a.to_string());
let b = Cow::Owned(b.to_string());
((a, b), n)
})
.collect();
// Make some non-'static &strs
let s1 = "e".to_string();
let s2 = "f".to_string();
let c1 = Cow::Borrowed(s1.as_str());
let c2 = Cow::Borrowed(s2.as_str());
// Do a lookup with borrowed Cows
map[&(c1, c2)]
Run Code Online (Sandbox Code Playgroud)
如果您需要指定Cow内部的生命周期HashMap,那应该是'static因为所有条目都是拥有的。这有一个很好的副作用,&'static str即允许条目和String条目。