43_pointers5.zig 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. //
  2. // Passing integer pointers around is generally not something you're going
  3. // to do. Integers are cheap to copy.
  4. //
  5. // But you know what IS useful? Pointers to structs:
  6. //
  7. // const Vertex = struct{ x: u32, y: u32, z: u32 };
  8. //
  9. // var v1 = Vertex{ .x=3, .y=2, .z=5 };
  10. //
  11. // var pv: *Vertex = &v1; // <-- a pointer to our struct
  12. //
  13. // Note that you don't need to dereference the "pv" pointer to access
  14. // the struct's fields:
  15. //
  16. // YES: pv.x
  17. // NO: pv.*.x
  18. //
  19. // We can write functions that take pointer arguments:
  20. //
  21. // fn foo(v: *Vertex) void {
  22. // v.x += 2;
  23. // v.y += 3;
  24. // v.z += 7;
  25. // }
  26. //
  27. // And pass references to them:
  28. //
  29. // foo(&v1);
  30. //
  31. //
  32. // Let's revisit our RPG example and make a printCharacter() function
  33. // that takes a Character pointer.
  34. //
  35. const std = @import("std");
  36. const Class = enum{
  37. wizard,
  38. thief,
  39. bard,
  40. warrior,
  41. };
  42. const Character = struct{
  43. class: Class,
  44. gold: u32,
  45. health: u8,
  46. experience: u32,
  47. };
  48. pub fn main() void {
  49. var glorp = Character{
  50. .class = Class.wizard,
  51. .gold = 10,
  52. .health = 100,
  53. .experience = 20,
  54. };
  55. // FIX ME!
  56. // Please pass our Character "glorp" to printCharacter():
  57. printCharacter( ??? );
  58. }
  59. // Note how this function's "c" parameter is a pointer to a Character struct.
  60. fn printCharacter(c: *Character) void {
  61. // Here's something you haven't seen before: when switching an enum, you
  62. // don't have to write the full enum name. Zig understands that ".wizard"
  63. // means "Class.wizard" when we switch on a Class enum value:
  64. const class_name = switch (c.class) {
  65. .wizard => "Wizard",
  66. .thief => "Thief",
  67. .bard => "Bard",
  68. .warrior => "Warrior",
  69. };
  70. std.debug.print("{s} (G:{} H:{} XP:{})", .{
  71. class_name,
  72. c.gold,
  73. c.health,
  74. c.experience,
  75. });
  76. }