簡體   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