052_slices.zig 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. //
  2. // We've seen that passing arrays around can be awkward. Perhaps you
  3. // remember a particularly horrendous function definition from quiz3?
  4. // This function can only take arrays that are exactly 4 items long!
  5. //
  6. // fn printPowersOfTwo(numbers: [4]u16) void { ... }
  7. //
  8. // That's the trouble with arrays - their size is part of the data
  9. // type and must be hard-coded into every usage of that type. This
  10. // digits array is a [10]u8 forever and ever:
  11. //
  12. // var digits = [10]u8{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
  13. //
  14. // Thankfully, Zig has slices, which let you dynamically point to a
  15. // start item and provide a length. Here are slices of our digit
  16. // array:
  17. //
  18. // const foo = digits[0..1]; // 0
  19. // const bar = digits[3..9]; // 3 4 5 6 7 8
  20. // const all = digits[0..]; // 0 1 2 3 4 5 6 7 8 9
  21. //
  22. // As you can see, a slice [x..y] defines a first item by index x and
  23. // a length y (where y-1 is the index of the last item). Leaving y off
  24. // gives you the rest of the items.
  25. //
  26. // Notice that the type of a slice on an array of u8 items is []u8.
  27. //
  28. const std = @import("std");
  29. pub fn main() void {
  30. var cards = [8]u8{ 'A', '4', 'K', '8', '5', '2', 'Q', 'J' };
  31. // Please put the first 4 cards in hand1 and the rest in hand2.
  32. const hand1: []u8 = cards[???];
  33. const hand2: []u8 = cards[???];
  34. std.debug.print("Hand1: ", .{});
  35. printHand(hand1);
  36. std.debug.print("Hand2: ", .{});
  37. printHand(hand2);
  38. }
  39. // Please lend this function a hand. A u8 slice hand, that is.
  40. fn printHand(hand: ???) void {
  41. for (hand) |h| {
  42. std.debug.print("{u} ", .{h});
  43. }
  44. }