rust - HashMap 中的生命周期,其中键指的是值

标签 rust

我对 Rust 比较陌生。我想编写一个函数,该函数将从一个集合中创建一个 HashMap,给定一个从值生成键的闭包,例如

[derive(Debug)]
struct Foo {
    id: u32,
    name: String,
}
let foos = vec![
    Foo { id: 1, name: "Bill".to_string() },
    Foo { id: 2, name: "Mary".to_string() },
];
println!("{:?}", foos);
println!("{:?}", map_by(foos.iter(), |f|  f.id));  // borrow  the Foos
println!("{:?}", map_by(foos.iter(), |f| &f.name));          // borrow
println!("{:?}", map_by(foos.iter(), |f|  f.name.as_str())); // borrow
println!("{:?}", map_by(foos,        |f|  f.id));  // consume the Foos

我写了这个,它适用于上述用途:

fn map_by<I,K,V>(iterable: I, f: impl Fn(&V) -> K) -> HashMap<K,V>
where I: IntoIterator<Item = V>,
      K: Eq + Hash
{
    iterable.into_iter().map(|v| (f(&v), v)).collect()
}

[Foo { id: 1, name: "Bill" }, Foo { id: 2, name: "Mary" }]
{1: Foo { id: 1, name: "Bill" }, 2: Foo { id: 2, name: "Mary" }}
{"Bill": Foo { id: 1, name: "Bill" }, "Mary": Foo { id: 2, name: "Mary" }}
{"Bill": Foo { id: 1, name: "Bill" }, "Mary": Foo { id: 2, name: "Mary" }}
{2: Foo { id: 2, name: "Mary" }, 1: Foo { id: 1, name: "Bill" }}

太棒了!但是当我让 HashMap 在键引用它们时拥有这些值时它不起作用:

println!("{:?}", map_by(foos,        |f| f.name.as_str()));

error[E0495]: cannot infer an appropriate lifetime for borrow expression due to conflicting requirements

不幸的是,错误信息让我的大脑崩溃了。我尝试指定键和值具有相同的生命周期,但没有帮助。 Here it is in a playground .编译器试图告诉我什么,我做错了什么?当然,如果这在我们借用值(value)时行得通,那么在我们拥有它们时也行得通。

最佳答案

Surely if this can work when we borrow the values, it can work when we own them.

没有。 HashMap 会在需要调整自身大小以容纳新条目时在内存中四处移动条目。如果键借用了值,并且移动了条目,则值的地址将改变并且键中的引用将不再有效。

有关详细信息,请参阅 Why can't I store a value and a reference to that value in the same struct? .

关于rust - HashMap 中的生命周期,其中键指的是值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61020835/

相关文章:

json - 无法从json反序列化chrono::DateTime

memory - 溢出主堆栈时的四种不同结果

regex - 使正则表达式量词的长度取决于先前的捕获组

rust - 将数据序列化到结构模型中,其中两个字段的数据是根据结构中的其他字段计算的

rust - 如何为具有特殊情况的枚举实现 `Hash`?

multithreading - 线程引用需要静态生命周期?

module - 如何将特征的实现拆分为多个文件?

rust - 在 Rust 中创建带有结构的 hashmap

rust - 指示 crate 生成的文档适用于哪个版本