Skip to content

Instantly share code, notes, and snippets.

@shimamura-sakura
Created April 20, 2024 16:17
Show Gist options
  • Save shimamura-sakura/dd7e00aff571b8b020859435b27dbe5f to your computer and use it in GitHub Desktop.
Save shimamura-sakura/dd7e00aff571b8b020859435b27dbe5f to your computer and use it in GitHub Desktop.
Zig init struct with a tuple (so you can init it without writing field name)
const std = @import("std");
pub fn StructFieldsTuple(comptime T: type) type {
var info = switch (@typeInfo(T)) {
.Struct => |st| st,
else => @compileError("T must be a struct"),
};
var newFields = info.fields[0..info.fields.len].*;
inline for (&newFields, 0..) |*f, i| f.name = std.fmt.comptimePrint("{}", .{i});
info.decls = &.{};
info.fields = &newFields;
info.is_tuple = true;
return @Type(.{ .Struct = info });
}
pub fn structTupleInit(comptime T: type, value: StructFieldsTuple(T)) T {
const info = switch (@typeInfo(T)) {
.Struct => |st| st,
else => @compileError("T must be a struct"),
};
var result: T = undefined;
inline for (info.fields, value) |f, v| @field(result, f.name) = v;
return result;
}
test "use case" {
const Vec3 = struct { x: f32, y: f32 = 1, z: f32 = 1 };
const vec3 = structTupleInit(Vec3, .{ 1, 2, 3 });
std.debug.print("{}\n", .{vec3});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment