我有两种结构类型:
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
});
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 = &.{},
} });
}