gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 10:14:40 34 4
gpt4 key购买 nike

菜鸟问题:

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

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] 相同的内存?

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

最佳答案

var a = arr.items[0];



那就是复制 arr.items[0] 中的项目.

如果您需要引用,请写 var a = &arr.items[0];反而。

关于arraylist - 在 Zig 中改变数组列表中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61134368/

34 4 0