有没有办法在 Zig 中合并结构类型/扩展结构?

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

我有两种结构类型:

const BaseStruct = struct {
    foo: f64,
    bar: f64
};

const AdditionalFields = struct {
    baz: u64,
};

是否有一种(最好是简单的)方法从前两种结构类型中创建(在编译时)第三种结构类型,这相当于

const ExtendedStruct = struct {
    foo: f64,
    bar: f64,
    baz: u64,
};

? (如果我希望所有三种结构类型都是

packed
怎么样?)

基本上,我想“扩展”

BaseStruct
,即创建带有附加字段的
BaseStruct
的“子类型”。

我正在想象这样的事情:

const ExtendedStruct = @mergeStruct(BaseStruct, AdditionalFields);

const ExtendedStruct = struct {
    ...BaseStruct, // unpacks (destructures) BaseStruct
    ...AdditionalFields, // Alternatively, write `baz: u64` directly
});
inheritance struct zig
1个回答
0
投票
fn Merge(comptime StructA: type, comptime StructB: type) type {
    const a_fields = @typeInfo(StructA).@"struct".fields;
    const b_fields = @typeInfo(StructB).@"struct".fields;

    return @Type(.{ .@"struct" = .{
        .layout = .auto,
        .fields = a_fields ++ b_fields,
        .is_tuple = false,
        .decls = &.{},
    } });
}
© www.soinside.com 2019 - 2024. All rights reserved.