043_pointers5.zig 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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 = 100, // <--- You can also provide fields a default value!
  46. experience: u32,
  47. };
  48. pub fn main() void {
  49. var glorp = Character{
  50. .class = Class.wizard,
  51. .gold = 10,
  52. .experience = 20,
  53. };
  54. // FIX ME!
  55. // Please pass our Character "glorp" to printCharacter():
  56. printCharacter(???);
  57. }
  58. // Note how this function's "c" parameter is a pointer to a Character struct.
  59. fn printCharacter(c: *Character) void {
  60. // Here's something you haven't seen before: when switching an enum, you
  61. // don't have to write the full enum name. Zig understands that ".wizard"
  62. // means "Class.wizard" when we switch on a Class enum value:
  63. const class_name = switch (c.class) {
  64. .wizard => "Wizard",
  65. .thief => "Thief",
  66. .bard => "Bard",
  67. .warrior => "Warrior",
  68. };
  69. std.debug.print("{s} (G:{} H:{} XP:{})", .{
  70. class_name,
  71. c.gold,
  72. c.health,
  73. c.experience,
  74. });
  75. }