gpt4 book ai didi

rust - 当它是 HashMap 中的键时,是否可以修改可变向量?

转载 作者:行者123 更新时间:2023-11-29 07:52:30 26 4
gpt4 key购买 nike

这是我的例子:

use std::collections::HashMap;

fn main() {
let mut my_map = HashMap::new();
let mut my_vec = vec![5,6,7];
my_map.insert(my_vec, 4);

// This part is fine, so I can create HashMap
// with mutable Vector as key.

my_vec.push(8);
}

但是,我实际上无法修改矢量! my_vec.push(8); 导致以下错误:

post_test_19.rs:14:5: 14:11 error: use of moved value: `my_vec` [E0382]
post_test_19.rs:14 my_vec.push(8);
^~~~~~
post_test_19.rs:7:19: 7:25 note: `my_vec` moved here because it has type `collections::vec::Vec<i32>`, which is non-copyable
post_test_19.rs:7 my_map.insert(my_vec, 4);
^~~~~~
error: aborting due to previous error

现在 HashMap 拥有 Vec,所以我不能修改它。

据我所知,如果 Vec 被用作 HashMap 中的键,即使它在技术上是可变的,你也不能修改它。我的理解正确吗?是否有我遗漏的技巧或极端情况?

最佳答案

不,你不能修改它,即使你可以,你绝对不应该做这样的事情。

在您的示例中,您无法修改矢量的原因是您不再拥有它。您已将其所有权转让给 map 。这就是“使用移动值”的意思。

假设您有一些方法可以修改 map 的键(我不会提供任何示例来帮助防止人们这样做)。主要问题是您会破坏 HashMap 的不变量:

It is a logic error for a key to be modified in such a way that the key's hash, as determined by the Hash trait, or its equality, as determined by the Eq trait, changes while it is in the map.

一旦您理解了 HashMap 的工作原理,其原因就很简单了。添加 key 时,会运行一种算法,将 key 转换为整数( key 是散列)。然后,这个整数用于在数组中找到一个空间来存储该值。

如果您更改了键,则值将存储在数组中的错误位置。举一个简单的例子,假设向量的哈希算法只是向量中的项目数。如果您添加 vec![1] 作为键,它将存储在数组槽 1 中。如果您随后更改键,它应该散列为 2,但会仍然存储在插槽 1 中!

关于rust - 当它是 HashMap 中的键时,是否可以修改可变向量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32162658/

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