Skip to content

Instantly share code, notes, and snippets.

@Lisoph
Created August 6, 2018 21:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Lisoph/6e5abfe7207673a28503df990d536b1e to your computer and use it in GitHub Desktop.
Save Lisoph/6e5abfe7207673a28503df990d536b1e to your computer and use it in GitHub Desktop.
Some fun with the Zig programming language
const std = @import("std");
const Controller = struct {
up: u1,
down: u1,
left: u1,
right: u1,
};
pub fn main() void {
structInfo(Controller);
structInfo(struct {});
listStructFields(Controller);
listStructFields(struct {
some_i32: i32,
my_controller: Controller,
ptr_to_controller: *Controller,
});
listStructFields(union { foo: i32 });
listStructFields(enum { Hello });
listStructFields(struct {});
}
fn structInfo(comptime T: type) void {
std.debug.warn("Size of {}: {}\n", @typeName(T), @intCast(u64, @sizeOf(T)));
}
fn listStructFields(comptime T: type) void {
const TypeId = @import("builtin").TypeId;
const strct = switch (@typeInfo(T)) {
TypeId.Struct => |s| s,
else => return,
};
std.debug.warn("Listing fields for {}:\n", @typeName(T));
if (strct.fields.len > 0) {
inline for (strct.fields) |field| {
std.debug.warn(" {}: {}\n", field.name, @typeName(field.field_type));
}
} else {
std.debug.warn(" no fields for struct.\n");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment