036_enums2.zig 1.9 KB

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