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 –
- An expression can be passed to
match
inside parenthesis. This could be a function returning multiple values. -
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. - Optionally, we can also use an
if
statement in aftercase
value to match it. - Values are matched from top to bottom through each
case
. - 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++.
Carbon Language Series
- Introduction to Carbon Language.
- How to define variables in Carbon.
- Primitive Types – Bool, Int, Float, String
- Tuple in Carbon
- Struct in Carbon
- Pointers in Carbon
- Operators in Carbon Language
- Conditions & Control Flow in Carbon
- Ternary Operator (if expression) in Carbon
- Switch conditional in Carbon using Match
- Loops in Carbon
- Functions in Carbon