在 Rust 中,我有一个HashMap
密钥是(String, String)
. 现在我有(&str, &str)
数据了。有什么方法可以将其用作查询而不使用String
s 吗?
我相当确定这是不可能的。但是如果你可以改变,你可以通过使用: (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
条目。
归档时间: |
|
查看次数: |
233 次 |
最近记录: |