067_comptime2.zig 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. //
  2. // We've seen that Zig implicitly performs some evaluations at
  3. // compile time. But sometimes you'll want to explicitly request
  4. // compile time evaluation. For that, we have a new keyword:
  5. //
  6. // . . . o . . * . . .
  7. // . * | . . . . . . * . .
  8. // --o-- comptime * | .. .
  9. // * | * . . . . --*-- . * .
  10. // . . . . . . . . . | . . .
  11. //
  12. // When placed before a variable declaration, 'comptime'
  13. // guarantees that every usage of that variable will be performed
  14. // at compile time.
  15. //
  16. // As a simple example, compare these two statements:
  17. //
  18. // var bar1 = 5; // ERROR!
  19. // comptime var bar2 = 5; // OKAY!
  20. //
  21. // The first one gives us an error because Zig assumes mutable
  22. // identifiers (declared with 'var') will be used at runtime and
  23. // we have not assigned a runtime type (like u8 or f32). Trying
  24. // to use a comptime_int of undetermined size at runtime is
  25. // a MEMORY CRIME and you are UNDER ARREST.
  26. //
  27. // The second one is okay because we've told Zig that 'bar2' is
  28. // a compile time variable. Zig will help us ensure this is true
  29. // and let us know if we make a mistake.
  30. //
  31. const print = @import("std").debug.print;
  32. pub fn main() void {
  33. //
  34. // In this contrived example, we've decided to allocate some
  35. // arrays using a variable count! But something's missing...
  36. //
  37. var count = 0;
  38. count += 1;
  39. var a1: [count]u8 = .{'A'} ** count;
  40. count += 1;
  41. var a2: [count]u8 = .{'B'} ** count;
  42. count += 1;
  43. var a3: [count]u8 = .{'C'} ** count;
  44. count += 1;
  45. var a4: [count]u8 = .{'D'} ** count;
  46. print("{s} {s} {s} {s}\n", .{a1, a2, a3, a4});
  47. // Builtin BONUS!
  48. //
  49. // The @compileLog() builtin is like a print statement that
  50. // ONLY operates at compile time. The Zig compiler treats
  51. // @compileLog() calls as errors, so you'll want to use them
  52. // temporarily to debug compile time logic.
  53. //
  54. // Try uncommenting this line and playing around with it
  55. // (copy it, move it) to see what it does:
  56. //@compileLog("Count at compile time: ", count);
  57. }