069_comptime4.zig 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. //
  2. // One of the more common uses of 'comptime' function parameters is
  3. // passing a type to a function:
  4. //
  5. // fn foo(comptime MyType: type) void { ... }
  6. //
  7. // In fact, types are ONLY available at compile time, so the
  8. // 'comptime' keyword is required here.
  9. //
  10. // Please take a moment put on the wizard hat which has been
  11. // provided for you. We're about to use this ability to implement
  12. // a generic function.
  13. //
  14. const print = @import("std").debug.print;
  15. pub fn main() void {
  16. // Here we declare arrays of three different types and sizes
  17. // at compile time from a function call. Neat!
  18. const s1 = makeSequence(u8, 3); // creates a [3]u8
  19. const s2 = makeSequence(u32, 5); // creates a [5]u32
  20. const s3 = makeSequence(i64, 7); // creates a [7]i64
  21. print("s1={any}, s2={any}, s3={any}\n", .{s1, s2, s3});
  22. }
  23. // This function is pretty wild because it executes at runtime
  24. // and is part of the final compiled program. The function is
  25. // compiled with unchanging data sizes and types.
  26. //
  27. // And yet it ALSO allows for different sizes and types. This
  28. // seems paradoxical. How could both things be true?
  29. //
  30. // To accomplish this, the Zig compiler actually generates a
  31. // separate copy of the function for every size/type combination!
  32. // So in this case, three different functions will be generated
  33. // for you, each with machine code that handles that specific
  34. // data size and type.
  35. //
  36. // Please fix this function so that the 'size' parameter:
  37. //
  38. // 1) Is guaranteed to be known at compile time.
  39. // 2) Sets the size of the array of type T (which is the
  40. // sequence we're creating and returning).
  41. //
  42. fn makeSequence(comptime T: type, ??? size: usize) [???]T {
  43. var sequence: [???]T = undefined;
  44. var i: usize = 0;
  45. while (i < size) : (i += 1) {
  46. sequence[i] = @intCast(T, i) + 1;
  47. }
  48. return sequence;
  49. }