036_enums2.zig 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. //
  2. // Enums are really just a set of numbers. You can leave the
  3. // numbering up to the compiler, or you can assign them
  4. // explicitly. You can even specify the numeric type used.
  5. //
  6. // const Stuff = enum(u8){ foo = 16 };
  7. //
  8. // You can get the integer out with a built-in function:
  9. //
  10. // var my_stuff: u8 = @enumToInt(Stuff.foo);
  11. //
  12. // Note how that built-in function starts with "@" just like the
  13. // @import() function we've been using.
  14. //
  15. const std = @import("std");
  16. // Zig lets us write integers in hexadecimal format:
  17. //
  18. // 0xf (is the value 15 in hex)
  19. //
  20. // Web browsers let us specify colors using a hexadecimal
  21. // number where each byte represents the brightness of the
  22. // Red, Green, or Blue component (RGB) where two hex digits
  23. // are one byte with a value range of 0-255:
  24. //
  25. // #RRGGBB
  26. //
  27. // Please define and use a pure blue value Color:
  28. const Color = enum(u32) {
  29. red = 0xff0000,
  30. green = 0x00ff00,
  31. blue = ???,
  32. };
  33. pub fn main() void {
  34. // Remember Zig's multi-line strings? Here they are again.
  35. // Also, check out this cool format string:
  36. //
  37. // {x:0>6}
  38. // ^
  39. // x type ('x' is lower-case hexadecimal)
  40. // : separator (needed for format syntax)
  41. // 0 padding character (default is ' ')
  42. // > alignment ('>' aligns right)
  43. // 6 width (use padding to force width)
  44. //
  45. // Please add this formatting to the blue value.
  46. // (Even better, experiment without it, or try parts of it
  47. // to see what prints!)
  48. std.debug.print(
  49. \\<p>
  50. \\ <span style="color: #{x:0>6}">Red</span>
  51. \\ <span style="color: #{x:0>6}">Green</span>
  52. \\ <span style="color: #{}">Blue</span>
  53. \\</p>
  54. \\
  55. , .{
  56. @enumToInt(Color.red),
  57. @enumToInt(Color.green),
  58. @enumToInt(???), // Oops! We're missing something!
  59. });
  60. }