Created
August 6, 2018 21:55
-
-
Save haudan/6e5abfe7207673a28503df990d536b1e to your computer and use it in GitHub Desktop.
Some fun with the Zig programming language
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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