052_slices.zig 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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 bar = digits[5..9]; // 5 6 7 8
  21. // const all = digits[0..]; // 0 1 2 3 4 5 6 7 8 9
  22. //
  23. // As you can see, a slice [x..y] starts with the index of the
  24. // first item at x and the last item at y-1. You can leave the y
  25. // off to get "the rest of the items".
  26. //
  27. // Notice that the type of a slice on an array of u8 items is []u8.
  28. //
  29. const std = @import("std");
  30. pub fn main() void {
  31. var cards = [8]u8{ 'A', '4', 'K', '8', '5', '2', 'Q', 'J' };
  32. // Please put the first 4 cards in hand1 and the rest in hand2.
  33. const hand1: []u8 = cards[???];
  34. const hand2: []u8 = cards[???];
  35. std.debug.print("Hand1: ", .{});
  36. printHand(hand1);
  37. std.debug.print("Hand2: ", .{});
  38. printHand(hand2);
  39. }
  40. // Please lend this function a hand. A u8 slice hand, that is.
  41. fn printHand(hand: ???) void {
  42. for (hand) |h| {
  43. std.debug.print("{u} ", .{h});
  44. }
  45. }
  46. //
  47. // Fun fact: Under the hood, slices are stored as a pointer to
  48. // the first item and a length.