是否可以为struct包含类型作为属性的对象创建分配?
例如
示例结构是
const Content = struct {
content: type,
name: []const u8,
};
Run Code Online (Sandbox Code Playgroud)
然后,我想分配内存,例如2*Content
我知道我可以使用
const list: [2]CustomElement = .{ Content{ .content = Type, .name = "test" }, Content{ .content = Type, .name = "test" } };
Run Code Online (Sandbox Code Playgroud)
但如何使用它们来实现同样的事情allocators呢?
这是行不通的。
comptime {
var list = std.ArrayList(Content).init(test_allocator);
try list.append(Content{ .content = MyType , .name = "test" });
}
Run Code Online (Sandbox Code Playgroud)
我收到错误
error: parameter of type '*std.array_list.ArrayListAligned(Content,null)' must be declared comptime
Run Code Online (Sandbox Code Playgroud)
简而言之
Box是否可以像Rust 中那样构建功能?
根据我的理解,我认为该语言中当前可用的分配器(在撰写本文时为 0.6.0)通常需要“comptime”类型参数,目前不允许这样做。
从当前有关 的文档comptime来看,关于type类型:
在 Zig 中,类型是一等公民。它们可以分配给变量,作为参数传递给函数,并从函数返回。然而,它们只能用在编译时已知的表达式中,这就是为什么上面代码片段中的参数 T 必须用 comptime 标记。
它看起来确实应该是可能的,因为我认为type必须有一个大小,并且您可能可以分配一个可以容纳它的结构。
看起来comptime分配确实是一个可能在即将推出的版本中支持的用例: 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
};
};
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2460 次 |
| 最近记录: |