我使用了一个复杂的键来表示HashMap
,这样的键由两部分组成,其中一部分是String
,如果不 for each 查找分配一个新的String
,我就无法理解如何通过HashMap::get
方法进行查找.
以下是一些代码:
#[derive(Debug, Eq, Hash, PartialEq)]
struct Complex {
n: i32,
s: String,
}
impl Complex {
fn new<S: Into<String>>(n: i32, s: S) -> Self {
Complex { n: n, s: s.into() }
}
}
fn main() {
let mut m = std::collections::HashMap::<Complex, i32>::new();
m.insert(Complex::new(42, "foo"), 123);
// OK, but allocates temporary String
assert_eq!(123, *m.get(&Complex::new(42, "foo")).unwrap());
}
问题在于最后的断言.它通过了,但需要临时的堆分配,因为如果不构造String
,我就无法构造Complex
.
为了消除这样的临时分配,Rust提供了Borrow
特征,HashMap::get
方法利用了Borrow
特征.我知道如何使用简单的 keys .例如,Rust Standard Library的PathBuf
通过在引擎盖下使用std::mem::transmute
实现了Borrow<Path>
,但我不知道如何使其适用于我的Complex
类型:
#[derive(Debug)]
struct Borrowable {
// ??? -- What goes here? Perhaps something like:
n: i32,
s1: &str, // ??? -- But what would the lifetime be? Or maybe:
s2: str, // ??? -- But how would I extend this to a complex type
// containing two or more strings?
}
impl Borrowable {
fn new(n: i32, s: &str) -> &Self {
// ??? -- What goes here? It must not allocate.
unimplemented!();
}
}
impl std::borrow::Borrow<Borrowable> for Complex {
fn borrow(&self) -> &Borrowable {
// ??? -- What goes here? How can I transmute a Complex into a
// &Borrowable?
unimplemented!();
}
}
这似乎是一个常见的用例,我怀疑我错过了关于Borrow
的重要信息,但我完全不知所措.