有没有办法在 Zig 中拥有给定结构的 ArrayList?

问题描述 投票:0回答:1

我考虑过学习一点 Zig 并尝试原型维护我创建的结构的

std.ArrayList
,但一直在获得
error{OutOfMemory}
。我已经尝试使用所有我必须搜索错误的各种组合的 Google-Fu,并将结构与 ArrayList 一起使用无济于事。

This question (Malloc to a List of Struct in Zig) 似乎是最接近的解决方案,但我宁愿事情是动态的,也不愿分配比我认为需要的更多的内存。

这是我写的代码,作为测试:

const std = @import("std");

const Backtrace = struct {
  node: usize, distance: u8
};

pub fn main() void {
  const allocator = std.heap.page_allocator;
  var backtrace = std.ArrayList(Backtrace).init(allocator);
  defer backtrace.deinit();

  const nodes = [_]usize{1, 3, 5, 7, 9, 11};

  for (nodes) |n,d| {
    std.debug.print("{}: {}\n", .{n, d});
    try backtrace.append(.{.node = n, .distance = @truncate(u8, d)});
  }
}

这段代码的灵感来自this issue (Search ArrayList of Structs in Zig).

这是我在终端中运行时得到的输出:

$> zig run allocations.zig
allocations.zig:16:5: error: expected type 'void', found 'error{OutOfMemory}'
    try backtrace.append(.{.node = n, .distance = @truncate(u8, d)});
    ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/opt/homebrew/Cellar/zig/0.10.1/lib/zig/std/mem/Allocator.zig:10:19: note: error set declared here
pub const Error = error{OutOfMemory};
                  ^~~~~~~~~~~~~~~~~~
allocations.zig:7:15: note: function cannot return an error
pub fn main() void {
              ^~~~
referenced by:
    comptime_0: /opt/homebrew/Cellar/zig/0.10.1/lib/zig/std/start.zig:59:50
    remaining reference traces hidden; use '-freference-trace' to see all reference traces

最后,以防万一,我使用的是安装了 Homebrew 的 Zig 版本

0.10.1

heap-memory zig
1个回答
0
投票

您的

main
函数声明不允许 errors。将
void
更改为
!void

pub fn main() !void
© www.soinside.com 2019 - 2024. All rights reserved.