Comptime
Blocks of code may be forcibly executed at compile time using the
comptime
keyword. In
this example, the variables x and y are equivalent.
Integer literals are of the type comptime_int
. These are special in that they
have no size (they cannot be used at runtime!), and they have arbitrary
precision. comptime_int
values coerce to any integer type that can hold them.
They also coerce to floats. Character literals are of this type.
comptime_float
is also available, which internally is an f128
. These cannot
be coerced to integers, even if they hold an integer value.
Types in Zig are values of the type type
. These are available at compile time.
We have previously encountered them by checking
@TypeOf
and comparing with
other types, but we can do more.
Function parameters in Zig can be tagged as being
comptime
. This means
that the value passed to that function parameter must be known at compile time.
Let’s make a function that returns a type. Notice how this function is
PascalCase, as it returns a type.
We can reflect upon types using the built-in
@typeInfo
, which takes
in a type
and returns a tagged union. This tagged union type can be found in
std.builtin.Type
(info on how to make use of imports and std later).
We can use the @Type
function to create a type from a
@typeInfo
.
@Type
is implemented for
most types but is notably unimplemented for enums, unions, functions, and
structs.
Here anonymous struct syntax is used with .{}
, because the T
in T{}
can be
inferred. Anonymous structs will be covered in detail later. In this example we
will get a compile error if the Int
tag isn’t set.
Returning a struct type is how you make generic data structures in Zig. The
usage of @This
is required
here, which gets the type of the innermost struct, union, or enum. Here
std.mem.eql
is
also used which compares two slices.
The types of function parameters can also be inferred by using anytype
in
place of a type. @TypeOf
can then be used on the parameter.
Comptime also introduces the operators ++
and **
for concatenating and
repeating arrays and slices. These operators do not work at runtime.