Get pointers to mutable items in ArrayList

Hi,

I want to use an ArrayList to own some mutable struct items. So I create the list like this, for example:

var entities = std.ArrayList(Entity).initCapacity(alloc, 10);

Then I append struct literal:

entities.append(alloc, .{...});

But when I try to get an item, I get a *const Entity:

const e = entities.items[0]

I would like to get a *Entity instead, so that I can mutate it. How can I do that? I suppose that I can make a ArrayList(&Entity) instead, but it made more sense to me to have the ArrayList own the structs so that I don’t have to manage memory twice.

Thanks!

You can simply do

const e = &entities.items[0];

and e will be of type *Entity.

When you did

const e = entities.items[0];

e was of type Entity and not *const Entity. It copied entities.items[0].
You probably got an error about using a *const Entity when expecting a *Entity because you used a method that expected a *Entity but when you did e.someMethod(...), it passed a pointer to e which is a constant.

1 Like

Thanks! I’m still getting some strange feedback from ZLS but it compiles and runs as expected.

1 Like