Rust Match statement

All the examples I can find online only show a match arm using a simple command. It doesn't seem to be as powerful as a C switch statement. In C I would so do something like:

switch(number) {

   case 1  :
      dostuff(number);
      do_more_stuff(number);
      do_even_more_stuff(number);
      break; /* optional */
	
   case 2  :
      create(s);
      label(s);
      destroy(s);
      printf("Some text");
      break; /* optional */
  
   default : 
   do_default_stuff();
}

So in C for case 1 I could run three different commands one after the other until it hits a break. I assume match has this ability, but I cannot find it documented anywhere. Is it possible? If so could I get an example?

The only thing that match doesn't have is fall-through.

match number {
    1 => {
        dostuff(number);
        do_more_stuff(number);
        do_even_more_stuff(number);
    },
    2 => {
        create(s);
        label(s);
        destroy(s);
        printf("Some text");
    },
    _ => do_default_stuff(),
}
6 Likes

To be clear, the ability to use blocks as match cases is by no means a feature of the match expression itself, but completely orthogonal one. In Rust anywhere an expression expected, a block is also permitted, because blocks are expressions.

6 Likes

Well it technically is, by some standards. Match arms that are blocks are uniquely able to omit the trailing comma; if match arms were truly decoupled from blocks then this wouldn't be allowed:

match num {
    0 => {}
    1 => { println!(); }
    _ => {}
} 

But for all practical purposes you can consider match arms to just be an expression like any other.

2 Likes

That's purely a syntactic special case, not a semantic feature. And you can also add the trailing comma anyway, so that it also looks like just an expression.

The exact opposite is true. Rust's match is much more powerful than C's switch. However, its power comes from the rich structure of pattern matching, not from the raw amount of code you can write in a match arm.

3 Likes