Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutating a value in an array list in Zig

Tags:

arraylist

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?

like image 451
aqui8 Avatar asked Apr 28 '26 03:04

aqui8


1 Answers

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.

like image 145
daurnimator Avatar answered Apr 29 '26 16:04

daurnimator



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!