Hi,
I’m trying to understand more about comptime and test it’s limits. I know that what I “want” is not how it should be done in production, but I am curious on how the general mechanic works. I hope it is ok, if I use a C-Macro example to explain what I want:
Question1
If I use C-Macros I can use #ifdef
to conditinally compile in code:
#define FOO
#ifdef FOO
int a = 42;
#endif
printf("%d\n", a);
This actually transforms the source code and if FOO is not defined the compilation will fail.
How to achieve this in zig? I tried something along those lines:
const foo = true;
if (comptime foo) {
const a: usize = 42;
}
std.debug.print("{d}\n", .{a});
I get an error during compilation because the variable a is not in scope anymore, as it was within the if-block. How can I create such a behavior (regardless whether it is a good idea).
Question2
Is it possible to define a string and create a variable name from it?
Something like:
#define NAME varname
int NAME = 3;
This will be transformed by the C-preprocessor to
int varname = 3;
I have no Idea how to tackle this in Zig. Maybe there exists some stdlib or builtin like
const name = "varname";
var @namefromstring(name) = 3;
Question 3
How can I build structs at compile time? All the examples I found seem to be from last year and out of date. I tried to tweak the stuff I found, but I do not know if I go into the right direction. Can someone please post a working example?
pub fn createtype() type {
var fields: [2]std.builtin.Type.StructField = undefined;
fields[0] = .{ //
.name = "a",
.type = bool,
.default_value = null,
.is_comptime = false,
.alignment = 0,
};
fields[1] = .{ //
.name = "b",
.type = i32,
.default_value = null,
.is_comptime = false,
.alignment = 0,
};
return @Type(.{
.Struct = .{
.layout = .Auto,
.fields = fields,
.decls = &.{},
.is_tuple = false,
.backing_integer = null,
},
});
}
const mytype = createtype();
pub fn main() !void {
std.debug.print("{?}\n", .{mytype{ .a = true, .b = 42 }});
}
Edit: Ok, with question three I was almost done. .Auto
→ .auto
and .fields
takes an address, so .fields = &fields
.
Thank you for your answers.