073_comptime8.zig 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. //
  2. // As a matter of fact, you can put 'comptime' in front of any
  3. // expression to force it to be run at compile time.
  4. //
  5. // Execute a function:
  6. //
  7. // comptime llama();
  8. //
  9. // Get a value:
  10. //
  11. // bar = comptime baz();
  12. //
  13. // Execute a whole block:
  14. //
  15. // comptime {
  16. // bar = baz + biff();
  17. // llama(bar);
  18. // }
  19. //
  20. // Get a value from a block:
  21. //
  22. // var llama = comptime bar: {
  23. // const baz = biff() + bonk();
  24. // break :bar baz;
  25. // }
  26. //
  27. const print = @import("std").debug.print;
  28. const llama_count = 5;
  29. const llamas = [llama_count]u32{ 5, 10, 15, 20, 25 };
  30. pub fn main() void {
  31. // We meant to fetch the last llama. Please fix this simple
  32. // mistake so the assertion no longer fails.
  33. const my_llama = getLlama(5);
  34. print("My llama value is {}.\n", .{my_llama});
  35. }
  36. fn getLlama(i: usize) u32 {
  37. // We've put a guard assert() at the top of this function to
  38. // prevent mistakes. The 'comptime' keyword here means that
  39. // the mistake will be caught when we compile!
  40. //
  41. // Without 'comptime', this would still work, but the
  42. // assertion would fail at runtime with a PANIC, and that's
  43. // not as nice.
  44. //
  45. // Unfortunately, we're going to get an error right now
  46. // because the 'i' parameter needs to be guaranteed to be
  47. // known at compile time. What can you do with the 'i'
  48. // parameter above to make this so?
  49. comptime assert(i < llama_count);
  50. return llamas[i];
  51. }
  52. // Fun fact: this assert() function is identical to
  53. // std.debug.assert() from the Zig Standard Library.
  54. fn assert(ok: bool) void {
  55. if (!ok) unreachable;
  56. }
  57. //
  58. // Bonus fun fact: I accidentally replaced all instances of 'foo'
  59. // with 'llama' in this exercise and I have no regrets!