Switch (Match) Conditional in Carbon Language

Total
0
Shares
switch match conditional in carbon language
Table of Contents Hide
  1. Introduction
  2. Code Example
  3. Conclusion

In Carbon language we don’t have switch statement. Else we have match. match is a control flow similar to switch of C and C++ and mirrors similar constructs in other languages, such as Swift.

Introduction

match has this structure –

match (expression) {
    case value => { 
       ...
       break;
    }
    default => {
       ...
       break;
    }
}

There are multiple things to understand here –

  1. An expression can be passed to match inside parenthesis. This could be a function returning multiple values.
  2. case uses the refutable pattern. The value of it is matched against the expression value. This could be multiple values with tuples or other data structures.
  3. Optionally, we can also use an if statement in after case value to match it.
  4. Values are matched from top to bottom through each case.
  5. If none matched then default runs.

Code Example

fn Bar() -> (i32, (f32, f32));

fn Foo() -> f32 {
  match (Bar()) {
    case (42, (x: f32, y: f32)) => {
      return x - y;
    }
    case (p: i32, (x: f32, _: f32)) if (p < 13) => {
      return p * x;
    }
    case (p: i32, _: auto) if (p > 3) => {
      return p * Pi;
    }
    default => {
      return Pi;
    }
  }
}

Here we declared two functions – Foo() and Bar().

Bar() is used for match expression. It is returning a tuple of 32 bit integer and a 2-tuple of 32 bit floats.

Foo() has the match conditional and it is returning a 32 bit integer value.

Let’s understand the match cases –

1. Bar() returns -> (i32, (f32, f32)). It means the case must match the tuple. Something like this –

case (12, (15.0, 18.5)) => {}

2. But, it’s possible to just match 1 value and discard other values or store them in variables. Like this –

case (12, (x: f32, y: f32)) => {}

3. It is also possible to completely discard a value –

case (12, _: auto) => {}

4. You can store the values in variable and then test conditions using if, like this –

case (a: i32, (x: f32, y: f32)) if(a > 12 or x == y) => {}

5. All the values stored in variables are available to the case body. So, a, x, y can be used for computation inside case.

Conclusion

In this article we learned how we can use switch conditional in carbon language with the help of match statement. We also saw how different situations are handled by case statements which were not possible earlier with C++.