gpt4 book ai didi

rust - 为 HashMap 使用复杂键时如何避免临时分配?

转载 作者:行者123 更新时间:2023-11-29 08:20:28 24 4
gpt4 key购买 nike

我正在为 HashMap 使用复杂的 key 这样 key 包含两部分,一部分是 String ,而且我不知道如何通过 HashMap::get 进行查找不分配新的方法 String每次查找。

这是一些代码:

#[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());
}

问题出在最后的断言上。它通过了,但它需要临时堆分配,因为我无法构造 Complex无需构建 String .

为了消除这样的临时分配,Rust 提供了 Borrow 特征,HashMap::get方法利用。我了解如何制作 Borrow为简单的键工作。例如,Rust 标准库的 PathBuf工具 Borrow<Path>通过使用 std::mem::transmute在引擎盖下,但我不知道如何让它为我的 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 的重要信息,但我完全不知所措。

最佳答案

听起来你想要这个。

Cow将接受 &strString .

use std::borrow::Cow;

#[derive(Debug, Eq, Hash, PartialEq)]
struct Complex<'a> {
n: i32,
s: Cow<'a, str>,
}

impl<'a> Complex<'a> {
fn new<S: Into<Cow<'a, str>>>(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);

assert_eq!(123, *m.get(&Complex::new(42, "foo")).unwrap());
}

关于生命周期参数的注释:

如果你不喜欢lifetime参数,你只需要使用&'static strString那么你可以使用 Cow<'static, str>并从 impl block 和结构定义中删除其他生命周期参数。

关于rust - 为 HashMap 使用复杂键时如何避免临时分配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51706783/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com