在Rust中使用Box<>和HashMap<>

我需要HashMap在 Rust 中创建一个 large ,这就是为什么我想到使用Box来使用堆内存。
我的问题是关于保留这些数据的最佳方式是什么,当然我只想到了两种可能的方式(预计我对 Rust 没有那么丰富的经验)。


fn main() {
  let hashmap = Box<HashMap<u64, DataStruct>>;
  ...
}

或者

fn main() {
  let hashmap = HashMap<u64, Box<DataStruct>>;
  ...
}

处理这种事情的最佳方法是什么?
非常感谢。

回答

HashMap 已经将它的数据存储在堆上,您不需要装箱您的值。

就像向量一样,哈希映射将它们的数据存储在堆上。此 HashMap 具有 String 类型的键和 i32 类型的值。像向量一样,哈希映射是同构的:所有的键必须具有相同的类型,并且所有的值必须具有相同的类型。

来源

  • Just to add: as a rule of thumb, almost anything that is *dynamic* will use the heap, because the stack has to be known at compile-time. That means things that can expand (Vecs and HashMaps, as you can add elements), that have an indeterministic life (Arcs and Rcs allocations, as they decide when to deallocate, based on reference counting), or that have an unknown size (trait objects, recursive structures) will be allocated on the heap, as they cannot be statically defined at compile-time.

以上是在Rust中使用Box&lt;&gt;和HashMap&lt;&gt;的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>