gpt4 book ai didi

allocator - 在 Zig lang 中分配通用结构

转载 作者:行者123 更新时间:2023-12-04 08:46:17 25 4
gpt4 key购买 nike

是否可以为 struct 创建分配包含类型作为属性?
例如
示例结构是

const Content = struct {
content: type,
name: []const u8,
};
然后,我想分配内存,例如 2 * Content我知道我可以用
const list: [2]CustomElement = .{ Content{ .content = Type, .name = "test" }, Content{ .content = Type, .name = "test" } };
但是如何使用 allocators 实现相同的目标?
这不起作用。
  comptime {
var list = std.ArrayList(Content).init(test_allocator);
try list.append(Content{ .content = MyType , .name = "test" });
}
我得到错误
error: parameter of type '*std.array_list.ArrayListAligned(Content,null)' must be declared comptime
简称
是否可以为 Box 之类的东西构建功能?在 Rust 中吗?

最佳答案

根据我的理解,我认为该语言中当前可用的分配器(撰写本文时为 0.6.0)通常需要一个“comptime”类型参数,目前不允许这样做。
从当前documentation关于comptime , 关于 type类型:

In Zig, types are first-class citizens. They can be assigned tovariables, passed as parameters to functions, and returned fromfunctions. However, they can only be used in expressions which areknown at compile-time, which is why the parameter T in the abovesnippet must be marked with comptime.


这似乎确实是可能的,因为我认为 type必须有一个大小,你可能会分配一个可以容纳它的结构。
它确实看起来像 comptime分配是 future 版本可能支持的用例: https://github.com/ziglang/zig/issues/1291 ,但我不确定这会如何与 type 互动.
我是 Zig 的新手,所以希望有人能提供更完整的答案 =D
编辑 :我确定这不是您要问的问题,但是如果像上面的示例一样,您只在列表中存储具有相同类型的对象,我想您可以用泛型做一些事情吗?
例如
const std = @import("std");

pub fn main() anyerror!void {
const cw = ContentWrapper(MyType);

var list = std.ArrayList(cw.Content).init(std.heap.page_allocator);
try list.append(cw.Content{ .content = MyType{ .id = 1, .property = 30 }, .name = "First" });
try list.append(cw.Content{ .content = MyType{ .id = 2, .property = 10 }, .name = "Second" });
}

const MyType = struct {
id: u8, property: f32
};

fn ContentWrapper(comptime T: type) type {
return struct {
pub const Content = struct {
content: T, name: []const u8
};
};
}

关于allocator - 在 Zig lang 中分配通用结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64301274/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com