Skip to content

Instantly share code, notes, and snippets.

@jackdbd
Last active April 11, 2023 09:00
Show Gist options
  • Save jackdbd/aa5236bb1d3fa5556327319fcdd5600a to your computer and use it in GitHub Desktop.
Save jackdbd/aa5236bb1d3fa5556327319fcdd5600a to your computer and use it in GitHub Desktop.
Function reflection in Zig
//! Example of function reflection in zig.
//!
//! 1. Compile this gist
//! zig build-exe reflection.zig -O Debug && ./reflection
//!
//! 2. Run the tests
//! zig test reflection.zig
const std = @import("std");
const Hello = struct {
foo: u32,
bar: []const u8,
};
pub fn main() void {
printInfoAboutStruct(Hello);
}
fn printInfoAboutStruct(comptime T: type) void {
const info = @typeInfo(T);
inline for (info.Struct.fields, 0..) |field, i| {
std.debug.print(
"type {s} field {d} is called '{s}' and is of type {any}\n",
.{ @typeName(T), i, field.name, field.type },
);
}
}
const expect = std.testing.expect;
const expectEqual = std.testing.expectEqual;
test "expect reflection" {
const T = @TypeOf(expect);
const info = @typeInfo(T);
try expect(info.Fn.params[0].type.? == bool);
try expect(info.Fn.return_type != void);
try expectEqual(info.Fn.is_var_args, false);
}
test "expectEqual reflection" {
const T = @TypeOf(expectEqual);
const info = @typeInfo(T);
try expect(info.Fn.return_type != void);
try expectEqual(info.Fn.is_var_args, false);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment