正如标题所说,我正在尝试迭代 2 个向量的 HashMap。我的代码如下:
pub fn serialize_hashmap(data: &HashMap<Vec<u8>, Vec<u8>>) -> Result<Vec<u8>, String> {
let mut serialized_data = Vec::new();
for (hash, password_data) in &data {
serialized_data.extend_from_slice(&hash);
let password_data_length: u64 = password_data.len().try_into().unwrap();
serialized_data.write_u64::<NativeEndian>(password_data_length).unwrap(); // TODO add error handling
serialized_data.extend_from_slice(&password_data);
}
return Ok(serialized_data);
}
但是当我运行此代码时,出现以下错误:
error[E0277]: the size for values of type `[_]` cannot be known at compilation time
--> src/main.rs:8:10
|
8 | for (hash, password_data) in &data {
| ^^^^ doesn't have a size known at compile-time
|
= help: the trait `Sized` is not implemented for `[_]`
= note: all local variables must have a statically known size
= help: unsized locals are gated as an unstable feature
error[E0277]: the size for values of type `[_]` cannot be known at compilation time
--> src/main.rs:8:34
|
8 | for (hash, password_data) in &data {
| ^^^^^ doesn't have a size known at compile-time
|
= help: the trait `Sized` is not implemented for `[_]`
= note: only the last element of a tuple may have a dynamically sized type
问题似乎是我的哈希图是动态分配的,并且其大小在运行时未知。即使 HashMap 是动态分配的,有什么方法可以迭代它吗?像这样的事情通常如何在 Rust 中完成?
我很确定你的问题只是
data
已经是一个引用,所以当你尝试迭代 &data
时,你正在迭代 &&HashMap
,这是不可迭代的。如果您删除 & 符号,使其成为 for ... in data
,我认为循环应该可以工作,因为它只是迭代 &HashMap
,这完全没问题。