在 Zig 中改变数组列表中的值

aqu*_*ui8 6 arraylist zig

菜鸟问题:

我想改变数组列表中存在的值。我最初尝试获取索引项并直接更改其字段值。

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;
}
Run Code Online (Sandbox Code Playgroud)

然而结果却出乎我的意料:

a: Foo{ .foo = 1 }
a: Foo{ .foo = 2 }
arr.items[0]: Foo{ .foo = 1 }
Run Code Online (Sandbox Code Playgroud)

我原以为arr.items[0]现在会等于Foo{ .foo = 2 }

这可能是因为我误解了切片。

a指向相同的内存吗arr.items[0]

是否arr.items[0]返回指向复制项的指针?

dau*_*tor 7

var a = arr.items[0];

即复制 中的项目arr.items[0]

如果您想要参考,请写var a = &arr.items[0];下来。