Advertisement
Guest User

Untitled

a guest
Oct 8th, 2018
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. ///////////////////////////////////////////////////////////////////////////////
  2. // Example 1:
  3. // Here, we create an enum, and switch on the enum in the toType function. This
  4. // returns another type that we can then use in the main() function. This
  5. // doesn't compile -
  6. // main.zig:28:24: error: unable to evaluate constant expression
  7. // const ThisEnumType = my_enum.toType();
  8. ///////////////////////////////////////////////////////////////////////////////
  9.  
  10.  
  11. const Foo = struct {};
  12. const Bar = struct {};
  13.  
  14. const MyEnum = enum {
  15. Foo,
  16. Bar,
  17.  
  18. /// This function switches on this enum and returns the corresponding type
  19. pub fn toType(self: MyEnum) type {
  20. return switch (self) {
  21. MyEnum.Foo => Foo,
  22. MyEnum.Bar => Bar,
  23. };
  24. }
  25. };
  26.  
  27. pub fn main() void {
  28. // Get an enum in some runtime way
  29. var my_enum = MyEnum.Foo;
  30. // Convert to type
  31. const ThisEnumType = my_enum.toType();
  32. // Now use this type
  33. var x : ThisEnumType = undefined;
  34. }
  35.  
  36. ///////////////////////////////////////////////////////////////////////////////
  37. // Example 2:
  38. // This is a similar example, but instead of switching inside the function
  39. // toType(), the function is inline in the main() function. This compiles.
  40. ///////////////////////////////////////////////////////////////////////////////
  41.  
  42. const Foo = struct {};
  43. const Bar = struct {};
  44.  
  45. const MyEnum = enum {
  46. Foo,
  47. Bar,
  48. };
  49.  
  50. pub fn main() void {
  51. // Get an enum in some runtime way
  52. var my_enum = MyEnum.Foo;
  53. const ThisEnumType = switch (my_enum) {
  54. MyEnum.Foo => Foo,
  55. MyEnum.Bar => Bar,
  56. };
  57. // Now use this type
  58. var x : ThisEnumType = undefined;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement