071_comptime6.zig 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. //
  2. // There have been several instances where it would have been
  3. // nice to use loops in our programs, but we couldn't because the
  4. // things we were trying to do could only be done at compile
  5. // time. We ended up having to do those things MANUALLY, like
  6. // NORMAL people. Bah! We are PROGRAMMERS! The computer should be
  7. // doing this work.
  8. //
  9. // An 'inline for' is performed at compile time, allowing you to
  10. // programatically loop through a series of items in situations
  11. // like those mentioned above where a regular runtime 'for' loop
  12. // wouldn't be allowed:
  13. //
  14. // inline for (.{ u8, u16, u32, u64 }) |T| {
  15. // print("{} ", .{@typeInfo(T).Int.bits});
  16. // }
  17. //
  18. // In the above example, we're looping over a list of types,
  19. // which are available only at compile time.
  20. //
  21. const print = @import("std").debug.print;
  22. // Remember Narcissus from exercise 065 where we used builtins
  23. // for reflection? He's back and loving it.
  24. const Narcissus = struct {
  25. me: *Narcissus = undefined,
  26. myself: *Narcissus = undefined,
  27. echo: void = undefined,
  28. };
  29. pub fn main() void {
  30. print("Narcissus has room in his heart for:", .{});
  31. // Last time we examined the Narcissus struct, we had to
  32. // manually access each of the three fields. Our 'if'
  33. // statement was repeated three times almost verbatim. Yuck!
  34. //
  35. // Please use an 'inline for' to implement the block below
  36. // for each field in the slice 'fields'!
  37. const fields = @typeInfo(Narcissus).@"struct".fields;
  38. ??? {
  39. if (field.type != void) {
  40. print(" {s}", .{field.name});
  41. }
  42. }
  43. // Once you've got that, go back and take a look at exercise
  44. // 065 and compare what you've written to the abomination we
  45. // had there!
  46. print(".\n", .{});
  47. }