071_comptime6.zig 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. var narcissus: Narcissus = Narcissus {};
  31. print("Narcissus has room in his heart for:", .{});
  32. // Last time we examined the Narcissus struct, we had to
  33. // manually access each of the three fields. Our 'if'
  34. // statement was repeated three times almost verbatim. Yuck!
  35. //
  36. // Please use an 'inline for' to implement the block below
  37. // for each field in the slice 'fields'!
  38. const fields = @typeInfo(Narcissus).Struct.fields;
  39. ??? {
  40. if (field.field_type != void) {
  41. print(" {s}", .{field.name});
  42. }
  43. }
  44. // Once you've got that, go back and take a look at exercise
  45. // 065 and compare what you've written to the abomination we
  46. // had there!
  47. print(".\n", .{});
  48. }