P H Kaznowski
P H Kaznowski

Reputation: 301

What is the correct way to reference memory in structs

I have a struct called Pizza. It contains a single Base struct and a vector of Topping structs.

I have a helper method that returns a Pizza. In the (near) future, I see the toppings being a collection somewhere and Pizzas being dynamically created from this collection of Toppings (mix and match style).

My question is about how the struct should reference Bases and Toppings. If I give ownership to the struct, then it makes it easy to handle it (no lifetime declarations, helper methods are also easier since they no longer need to create the memory outside of scope). However by having Toppings outside of scope of my helper method and declaring lifetimes I get less repetition in memory.

How do people reason about these problems? Is there a recommended rule of thumb to follow? Is it possible to have both?

Upvotes: 0

Views: 63

Answers (1)

Kornel
Kornel

Reputation: 100100

If Topping is small (e.g. an enum), then you can just copy it (e.g. into Vec<Topping>).

If Topping is large and you want only one copy in memory, the easiest to work with is to use Arc<Topping> which is a shared pointer, and can be cheaply cloned and easily passed around (e.g. into Vec<Arc<Topping>>).

If both Pizza and Topping are used only in a specific statically-known scope (e.g. you create all toppings in main() and don't change them later, or you use a memory pool), you may get away with using &'a Topping in Pizza<'a>, but this is likely to be unnoticeably small performance improvement compared to Rc/Arc, and keeping track of the temporary lifetime will be annoying.

Upvotes: 1

Related Questions