3 ms·
comptime is hard to grasp from that blurb. for c programmers, here's a good example: you know how gcc will usually optimize `memcpy(dest, src, strlen("hello"))
by woodrowbarlow 5y ago
comptime is hard to grasp from that blurb. for c programmers, here's a good example:
you know how gcc will usually optimize `memcpy(dest, src, strlen("hello"))` to just `memcpy(dest, src, 5)` -- because it knows how strlen works, and in this case all the inputs are known at compile time?
well, in zig, if a function is pure and all of its inputs are known at compile time, the compiler will always run the function at compile time and replace the function call with the result. you can also add the keyword `comptime` to force this behavior on a per-statement basis.
so comptime gives you conditional compilation and also results in more optimized code. coupled with zig's import system, this eliminates the need for a preprocessor. perhaps more interestingly: even types can be comptimed... which gives you generics 'for free'.
edit: removed inaccurate assumption regarding qemu
- ifreund 5y ago> it actually builds a stub program and runs it in qemu for your target arch That's not at all how the implementation works, the zig compiler does not depend on qemu. The comptime evaluation works much more like evaluating an interpreted language such as python.
- AnIdiotOnTheNet 5y agoTo provide a simple example of how comptime is used for generics in Zig, consider the ArrayList. Idiomatic Zig code uses TitleCase for types, but ArrayList is technically a function with the signature `ArrayList(comptime T: type) type`. Given the type `T` as an argument, it returns a new type `ArrayList(T)` that implements the ArrayList for `T`. You can initialize a new ArrayList of `Foo`s like this: `var list = ArrayList(Foo).init(allocator);`. No second macro language, no magic variables, no special syntax.