Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ///////////////////////////////////////////////////////////////////////////////
- // Example 1:
- // Here, we create an enum, and switch on the enum in the toType function. This
- // returns another type that we can then use in the main() function. This
- // doesn't compile -
- // main.zig:28:24: error: unable to evaluate constant expression
- // const ThisEnumType = my_enum.toType();
- ///////////////////////////////////////////////////////////////////////////////
- const Foo = struct {};
- const Bar = struct {};
- const MyEnum = enum {
- Foo,
- Bar,
- /// This function switches on this enum and returns the corresponding type
- pub fn toType(self: MyEnum) type {
- return switch (self) {
- MyEnum.Foo => Foo,
- MyEnum.Bar => Bar,
- };
- }
- };
- pub fn main() void {
- // Get an enum in some runtime way
- var my_enum = MyEnum.Foo;
- // Convert to type
- const ThisEnumType = my_enum.toType();
- // Now use this type
- var x : ThisEnumType = undefined;
- }
- ///////////////////////////////////////////////////////////////////////////////
- // Example 2:
- // This is a similar example, but instead of switching inside the function
- // toType(), the function is inline in the main() function. This compiles.
- ///////////////////////////////////////////////////////////////////////////////
- const Foo = struct {};
- const Bar = struct {};
- const MyEnum = enum {
- Foo,
- Bar,
- };
- pub fn main() void {
- // Get an enum in some runtime way
- var my_enum = MyEnum.Foo;
- const ThisEnumType = switch (my_enum) {
- MyEnum.Foo => Foo,
- MyEnum.Bar => Bar,
- };
- // Now use this type
- var x : ThisEnumType = undefined;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement