Ziglings exercise about the new Zig feature 'labeled switch'

For the new Zig feature ‘labeled switch’ we received an exercise from a new contributor. Great work!

Try out:

// By combining while loops and switch statements with continue and break statements
// one can create very concise State Machines.
//
// One such example would be:
//
//      pub fn main() void {
//          var op: u8 = 1;
//          while (true) {
//              switch (op) {
//                  1 => { op = 2; continue; },
//                  2 => { op = 3; continue; },
//                  3 => return,
//                  4 => {},
//              }
//              break;
//          }
//      std.debug.print("This statement cannot be reached");
//      }
//
// By combining all we've learned so far, we can now proceed with a labeled switch

Exercise 108 labeled switch

Ziglings - Learn the :zap:Zig programming language by fixing tiny broken programs.

15 Likes

@as(PullRequestState, PullRequestState.Draft)

This pains me /hj

2 Likes

Thanks, fixed it.

This inspired me to re-write zdt’s datetime string parser (and formatter) :slight_smile: I had this on my list for a while now, with the goal of better maintainability and the possibility to have a modifier à la Rust chrono strftime. It’s still a bit rough around the edges but so far is working out well.

In general, the labeled-switch state-machine reminds me of a case structure based state-machine you can build in LabVIEW, and also the function-that-returns-function state-machine in go (talk by Rob Pike). Pretty cool!

3 Likes