繁体   English   中英

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

[英]Mutating a value in an array list in 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;
}

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

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

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

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

a是否指向与arr.items[0]相同的 memory ?

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

var a = arr.items[0];

这是在arr.items[0]中制作项目的副本。

如果你想要一个参考,写var a = &arr.items[0]; 反而。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM