Design pattern: instead of giving a `*mut` to Child, return enum of actions for Parent to conduct

Hi guys,

I have managed to get around my only use of unsafe (*mut) by instead of letting the child mutate the data directly; pass back a vec of enums of actions to be taken, and have the parent conduct them instead.

however this requires a vec instantiation and allocation every time.

so...

  1. would it work better if the parent passed the child a &mut vec to allocate into?
    1b) is there a way to 'pop()' items off (i don't care which order) that doesn't mess with the capacity?

  2. i know the at most number of enums that will be returned.. but it's unlikely to reach that number often... should it return an array? or write into a &mut array kept by the parent?

  3. what about something like tinyvec here or any other solution... std::borrow::cow?
    3b) If it helps, Child is the only person who will ever mutate that data, if say, i could give him a permanent &mut that would be fine, i guess?

  4. also, what is the name of this pattern i am describing?

You can pop items off a Vec using the pop() method. There's also drain(). Neither will touch the capacity.

1 Like

nice, okay, but is it still better to pass in a popped Vec, rather than having the Child create a new Vec every time?

If nothing else is ever going to use the data, again, then by all means, move it into the function to transfer ownership. Borrows are only for temporarily lending out the right to use a value, but that doesn't seem to be what you want.

well i could also just pass it as a &mut argument.

I'm just looking for a nice speedy way to do this because I'm sad about the loss of my *mut and having to do lots of allocation etc

Yes, better to reuse, then the storage for the Vec doesn’t need to be reallocated. Vecs only release storage space when shrink_to_fit or similar is called

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.