Search code examples
arraylistzig

Mutating a value in an array list in Zig


Noob question:

I want to mutate a value that exists in an array list. I initially tried to just grab the indexed item and directly change its field value.

const Foo = struct {
    const Self = @This();

    foo: u8,
};

pub fn main() anyerror!void {
    const foo = Foo {
      .foo = 1,
    };

    const allocator = std.heap.page_allocator;

    var arr = ArrayList(Foo).init(allocator);

    arr.append(foo) catch unreachable;

    var a = arr.items[0];

    std.debug.warn("a: {}", .{a});

    a.foo = 2;

    std.debug.warn("a: {}", .{a});                                                                                                                                                                                                                                                                                       
    std.debug.warn("arr.items[0]: {}", .{arr.items[0]});

    //In order to update the memory in [0] I have to reassign it to a.
    //arr.items[0] = a;
}

However, the result is unexpected to me:

a: Foo{ .foo = 1 }
a: Foo{ .foo = 2 }
arr.items[0]: Foo{ .foo = 1 }

I would have thought that arr.items[0] would now equal Foo{ .foo = 2 }.

This is probably because I misunderstand slices.

Does a not point to the same memory as arr.items[0]?

Does arr.items[0] return a pointer to a copied item?


Solution

  • var a = arr.items[0];

    That is making a copy of the item in arr.items[0].

    If you want a reference, write var a = &arr.items[0]; instead.