loading

Match Operator

Match Operator

We can compare a value with a range of patterns using the match operator, which also runs the code if a match is detected. Among many other things, the patterns can be literal values, variable names, wildcards, and more.

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
				
			

Computerlanguage is a custom data type in the example above. It comes in four variants: C, Cplus, Java, and Csharp. The expressions provided in the match operator block are matched by the match operator with the value of the language.

Matching with Option

When we wish to extract the inner value of T from a particular case, we utilize option<T>.

The Option<T> consists of two variants:

  • None: It shows the inadequacy or lack of significance.
  • Some(value): The value is wrapped in T by a tuple struct.

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

Matches in Rust are exhaustive, meaning that in order for the code to work, we must exhaust every scenario. For example, the Rust compiler will display the error “pattern ‘None’ not covered” if we fail to write the None case.

Example:

				
					 fn main()  
{  
 Some(5);  
}  
fn Value(n:Option<i32>)  
{  
  match n  
  {  
    Some(n)=>println!("{}is a Number",n),  
  }  
}  
				
			

Output:

Match Operator -
Share this Doc

Match Operator

Or copy link

Explore Topic