If I make a struct and put it in a vector, does it reside on the heap or the stack?

懵懂的女人 提交于 2019-12-10 23:14:42

问题


I'm writing some code that generates a vector of geometric elements:

struct Geom_Entity {
    // a bunch of geometric information,
    // like tangent planes, force vectors, etc
}

The code is parsing many of these entities from a text file (for e.g.) so we have a function currently:

parse_Geom(x: String) -> Vec<Geom_Entity> { 
    // a bunch of code
}

These geometric entities are large structs with 17 f64s and a few other fields. The file may contain well over 1000 of these, but not so many that they can't all fit into memory (at least for now).

Also, should I be doing

Box::new(Geom_Entity { ...

and then putting the box in the vector?


回答1:


The documentation for Vec says (emphasis mine):

If a Vec has allocated memory, then the memory it points to is on the heap

So yes, the members of the vector are owned by the vector and are stored on the heap.


In general, boxing an element before putting it in the Vec is wasteful - there's extra memory allocation and indirection. There are times when you need that extra allocation or indirection, so it's never say never.

See also:

  • Does Rust box the individual items that are added to a vector?


来源:https://stackoverflow.com/questions/43641728/if-i-make-a-struct-and-put-it-in-a-vector-does-it-reside-on-the-heap-or-the-sta

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!