070_comptime5.zig 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. //
  2. // Being able to pass types to functions at compile time lets us
  3. // generate code that works with multiple types. But it doesn't
  4. // help us pass VALUES of different types to a function.
  5. //
  6. // For that, we have the 'anytype' placeholder, which tells Zig
  7. // to infer the actual type of a parameter at compile time.
  8. //
  9. // fn foo(thing: anytype) void { ... }
  10. //
  11. // Then we can use builtins such as @TypeOf(), @typeInfo(),
  12. // @typeName(), @hasDecl(), and @hasField() to determine more
  13. // about the type that has been passed in. All of this logic will
  14. // be performed entirely at compile time.
  15. //
  16. const print = @import("std").debug.print;
  17. // Let's define three structs: Duck, RubberDuck, and Duct. Notice
  18. // that Duck and RubberDuck both contain waddle() and quack()
  19. // methods declared in their namespace (also known as "decls").
  20. const Duck = struct {
  21. eggs: u8,
  22. loudness: u8,
  23. location_x: i32 = 0,
  24. location_y: i32 = 0,
  25. fn waddle(self: Duck, x: i16, y: i16) void {
  26. self.location_x += x;
  27. self.location_y += y;
  28. }
  29. fn quack(self: Duck) void {
  30. if (self.loudness < 4) {
  31. print("\"Quack.\" ", .{});
  32. } else {
  33. print("\"QUACK!\" ", .{});
  34. }
  35. }
  36. };
  37. const RubberDuck = struct {
  38. in_bath: bool = false,
  39. location_x: i32 = 0,
  40. location_y: i32 = 0,
  41. fn waddle(self: RubberDuck, x: i16, y: i16) void {
  42. self.location_x += x;
  43. self.location_y += y;
  44. }
  45. fn quack(self: RubberDuck) void {
  46. print("\"Squeek!\" ", .{});
  47. }
  48. fn listen(self: RubberDuck, dev_talk: []const u8) void {
  49. // Listen to developer talk about programming problem.
  50. // Silently contemplate problem. Emit helpful sound.
  51. self.quack();
  52. }
  53. };
  54. const Duct = struct {
  55. diameter: u32,
  56. length: u32,
  57. galvanized: bool,
  58. connection: ?*Duct = null,
  59. fn connect(self: Duct, other: *Duct) !void {
  60. if (self.diameter == other.diameter) {
  61. self.connection = other;
  62. } else {
  63. return DuctError.UnmatchedDiameters;
  64. }
  65. }
  66. };
  67. const DuctError = error{UnmatchedDiameters};
  68. pub fn main() void {
  69. // This is a real duck!
  70. const ducky1 = Duck{
  71. .eggs = 0,
  72. .loudness = 3,
  73. };
  74. // This is not a real duck, but it has quack() and waddle()
  75. // abilities, so it's still a "duck".
  76. const ducky2 = RubberDuck{
  77. .in_bath = false,
  78. };
  79. // This is not even remotely a duck.
  80. const ducky3 = Duct{
  81. .diameter = 17,
  82. .length = 165,
  83. .galvanized = true,
  84. };
  85. print("ducky1: {}, ", .{isADuck(ducky1)});
  86. print("ducky2: {}, ", .{isADuck(ducky2)});
  87. print("ducky3: {}\n", .{isADuck(ducky3)});
  88. }
  89. // This function has a single parameter which is inferred at
  90. // compile time. It uses builtins @TypeOf() and @hasDecl() to
  91. // perform duck typing ("if it walks like a duck and it quacks
  92. // like a duck, then it must be a duck") to determine if the type
  93. // is a "duck".
  94. fn isADuck(possible_duck: anytype) bool {
  95. // We'll use @hasDecl() to determine if the type has
  96. // everything needed to be a "duck".
  97. //
  98. // In this example, 'has_increment' will be true if type Foo
  99. // has an increment() method:
  100. //
  101. // const has_increment = @hasDecl(Foo, "increment");
  102. //
  103. // Please make sure MyType has both waddle() and quack()
  104. // methods:
  105. const MyType = @TypeOf(possible_duck);
  106. const walks_like_duck = ???;
  107. const quacks_like_duck = ???;
  108. const is_duck = walks_like_duck and quacks_like_duck;
  109. if (is_duck) {
  110. // We also call the quack() method here to prove that Zig
  111. // allows us to perform duck actions on anything
  112. // sufficiently duck-like.
  113. //
  114. // Because all of the checking and inference is performed
  115. // at compile time, we still have complete type safety:
  116. // attempting to call the quack() method on a struct that
  117. // doesn't have it (like Duct) would result in a compile
  118. // error, not a runtime panic or crash!
  119. possible_duck.quack();
  120. }
  121. return is_duck;
  122. }