Theoretical Paper
- Computer Organization
- Data Structure
- Digital Electronics
- Object Oriented Programming
- Discrete Mathematics
- Graph Theory
- Operating Systems
- Software Engineering
- Computer Graphics
- Database Management System
- Operation Research
- Computer Networking
- Image Processing
- Internet Technologies
- Micro Processor
- E-Commerce & ERP
- Dart Programming
- Flutter Tutorial
- Numerical Methods Tutorials
- VueJS
- Go
Practical Paper
Industrial Training
Match Operator
The match operator allows us to compare a value against a series of patterns, and executes the code whenever the match is found. The patterns can be literal values, variable names, wildcards and many other things.
Let's understand the match operator through a simple example:
enum Computerlanguage { C, Cplus, Java, Csharp, } fn language(language:Computerlanguage) { match language { Computerlanguage::C=> println!("C language"), Computerlanguage::Cplus=> println!("C++ language"), Computerlanguage::Java=> println!("Java language"), Computerlanguage::Csharp=> println!("C# language"), } } fn main() { language(Computerlanguage::C); language(Computerlanguage::Cplus); language(Computerlanguage::Java); language(Computerlanguage::Csharp); }
Output:
C language C++ language Java language C# language
In the above example, Computerlanguage is a custom data type which consists of four variants are C, Cplus, Java, Csharp. The match operator matches the value of the language with the expressions given in the match operator block.
Matching with Option< T>
Option< T> is used when we want to get the inner value of T out of some case.
The Option< T> consists of two variants:
-
None: It indicates the failure or lack of value.
Some(value): It is a tuple struct that wraps the value with T.
Let's understand through an example:
fn main() { even_number(2); even_number(3); } fn even_number(n:i32) { let num=n; match checked_even(n) { None=>println!("None"), Some(n)=> { if n==0 { println!("{} is a even number",num); } else { println!("{} is a odd number",num); }}, } } fn checked_even(number:i32)->Option< i32> { Some(number%2) }
Output:
2 is a even number 3 is a odd number
Matches are exhaustive
In Rust, matches are exhaustive, i.e., we should exhaust every possible case for the code to be valid. Suppose we forget to write the None case then the Rust compiler will show the bug that "pattern 'None' not covered".
Let's understand this case through an example:
fn main() { Some(5); } fn Value(n:Option) { match n { Some(n)=>println!("{}is a Number",n), } }
Output: