080_anonymous_structs.zig 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. //
  2. // Struct types are always "anonymous" until we give them a name:
  3. //
  4. // struct {};
  5. //
  6. // So far, we've been giving struct types a name like so:
  7. //
  8. // const Foo = struct {};
  9. //
  10. // * The value of @typeName(Foo) is "Foo".
  11. //
  12. // A struct is also given a name when you return it from a
  13. // function:
  14. //
  15. // fn Bar() type {
  16. // return struct {};
  17. // }
  18. //
  19. // const MyBar = Bar(); // store the struct type
  20. // const bar = Bar() {}; // create instance of the struct
  21. //
  22. // * The value of @typeName(Bar()) is "Bar()".
  23. // * The value of @typeName(MyBar) is "Bar()".
  24. // * The value of @typeName(@TypeOf(bar)) is "Bar()".
  25. //
  26. // You can also have completely anonymous structs. The value
  27. // of @typeName(struct {}) is "struct:<position in source>".
  28. //
  29. const print = @import("std").debug.print;
  30. // This function creates a generic data structure by returning an
  31. // anonymous struct type (which will no longer be anonymous AFTER
  32. // it's returned from the function).
  33. fn Circle(comptime T: type) type {
  34. return struct {
  35. center_x: T,
  36. center_y: T,
  37. radius: T,
  38. };
  39. }
  40. pub fn main() void {
  41. //
  42. // See if you can complete these two variable initialization
  43. // expressions to create instances of circle struct types
  44. // which can hold these values:
  45. //
  46. // * circle1 should hold i32 integers
  47. // * circle2 should hold f32 floats
  48. //
  49. var circle1 = ??? {
  50. .center_x = 25,
  51. .center_y = 70,
  52. .radius = 15,
  53. };
  54. var circle2 = ??? {
  55. .center_x = 25.234,
  56. .center_y = 70.999,
  57. .radius = 15.714,
  58. };
  59. print("[{s}: {},{},{}] ", .{
  60. @typeName(@TypeOf(circle1)),
  61. circle1.center_x,
  62. circle1.center_y,
  63. circle1.radius,
  64. });
  65. print("[{s}: {d:.1},{d:.1},{d:.1}]\n", .{
  66. @typeName(@TypeOf(circle2)),
  67. circle2.center_x,
  68. circle2.center_y,
  69. circle2.radius,
  70. });
  71. }