074_comptime9.zig 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. //
  2. // In addition to knowing when to use the 'comptime' keyword,
  3. // it's also good to know when you DON'T need it.
  4. //
  5. // The following contexts are already IMPLICITLY evaluated at
  6. // compile time, and adding the 'comptime' keyword would be
  7. // superfluous, redundant, and smelly:
  8. //
  9. // * The global scope (outside of any function in a source file)
  10. // * Type declarations of:
  11. // * Variables
  12. // * Functions (types of parameters and return values)
  13. // * Structs
  14. // * Unions
  15. // * Enums
  16. // * The test expressions in inline for and while loops
  17. // * An expression passed to the @cImport() builtin
  18. //
  19. // Work with Zig for a while, and you'll start to develop an
  20. // intuition for these contexts. Let's work on that now.
  21. //
  22. // You have been given just one 'comptime' statement to use in
  23. // the program below. Here it is:
  24. //
  25. // comptime
  26. //
  27. // Just one is all it takes. Use it wisely!
  28. //
  29. const print = @import("std").debug.print;
  30. // Being in the global scope, everything about this value is
  31. // implicitly required to be known compile time.
  32. const llama_count = 5;
  33. // Again, this value's type and size must be known at compile
  34. // time, but we're letting the compiler infer both from the
  35. // return type of a function.
  36. const llamas = makeLlamas(llama_count);
  37. // And here's the function. Note that the return value type
  38. // depends on one of the input arguments!
  39. fn makeLlamas(count: usize) [count]u8 {
  40. var temp: [count]u8 = undefined;
  41. var i = 0;
  42. // Note that this does NOT need to be an inline 'while'.
  43. while (i < count) : (i += 1) {
  44. temp[i] = i;
  45. }
  46. return temp;
  47. }
  48. pub fn main() void {
  49. print("My llama value is {}.\n", .{llamas[2]});
  50. }
  51. //
  52. // The lesson here is to not pepper your program with 'comptime'
  53. // keywords unless you need them. Between the implicit compile
  54. // time contexts and Zig's aggressive evaluation of any
  55. // expression it can figure out at compile time, it's sometimes
  56. // surprising how few places actually need the keyword.