Difference between revisions of "Rust-Programming-Language/C2/Pattern-Matching/English"
(Created page with "{| border="1" |- || '''Visual Cue''' || '''Narration''' |- || '''Slide 1''' || <span style="color:#000000;">Welcome to the Spoken Tutorial on </span><span style="color:#00000...") |
(No difference)
|
Revision as of 18:34, 22 August 2025
| Visual Cue | Narration |
| Slide 1 | Welcome to the Spoken Tutorial on Pattern Matching in Rust. |
| Slide 2:
Learning Objective
|
In this tutorial, we will learn about
|
| Slide:
Code Files
|
|
| Slide:
Pattern Matching syntax:
match VALUE {
PATTERN => EXPRESSION,
PATTERN => EXPRESSION,
PATTERN => EXPRESSION,
}
|
This is the syntax for the pattern matching.
|
| Open Visual code editor | Let us open the visual code editor and understand how pattern matching works. |
| >cd Desktop/MyRustProject | Go to our working directory MyRustProject as explained earlier.
Type the command cargo new pattern Open the created project.
In the main.rs file, replace the code as shown. |
| fn main() {
let x = 3;
match x {
1 => println!("One!"),
2 => println!("Two!"),
3 => println!("Three!"),
_ => println!("Something else!"),
}
}
|
The match statement is used to compare x against different patterns i.e (1 or 2 or 3).
underscore pattern is a catch-all pattern. It matches any other value not explicitly covered by previous patterns. In this case, it will print "Something else!", if x is not 1, 2, or 3. Save the code. Let us execute and see the result.
|
| In the menu bar, click on terminal and select New Terminal. | |
| Type Cargo build | In the terminal, type cargo run.
We can see the output as ‘Three’ which matches the pattern as per the x value. Let us change the value of x to 10 in the code.
|
| Save the code and run the program.
We can see the output as “something else” as expected.
| |
| The most common case for pattern matching is with Option and Result enum types. | |
| Slide:
Matching Option and Result type
|
Option and Result type have two variants. Option type has:
None →It is used to indicate failure with no value
Some(T) → It returns a value with type T
Result type has:
Ok(T) → It indicates operation succeeded with value T
Err(E) → It indicates operation failed with an error E
|
| Let us see an example for Matching Option Type in Rust.
Switch back to the Visual Code editor. | |
| fn main() {
fn first_element(array: &[i32]) -> Option<i32> {
if array.len() > 0 {
Some(array[0])
} else {
None
}
}
let array = [];
println!("{:?}", first_element(&array));
}
|
Copy and paste the code from the codefile.
Here the function first_element, returns the first element of an integer array if it exists. It takes a reference to an array of integers (&[i32]) as its parameter and returns an Option<i32>. The function checks the length of the array using array.len(). If the array has one or more elements, it returns Some(array[0]), i.e the first element of the array. If the array is empty, it returns None, indicating that there is no first element to return. Save the file.
|
| In the terminal, type cargo run and see the output.
None is displayed as output as the array is empty in the program. | |
| Let us add 10,20,30 as array elements in the code.
Save the program and run it again. Now it displays the first element of the array as 10. | |
| Next we will see about the Result enum type. | |
| fn main() {
fn divide(dividend: i32, divisor: i32) -> Result<i32, String> {
if divisor == 0 {
Err(String::from("Cannot divide by zero"))
} else {
Ok(dividend / divisor)
}
}
let result = divide(10, 2);
match result {
Ok(value) => println!("Result: {}", value),
Err(error) => println!("Error: {}", error),}
|
Copy and paste the code from the codefile.
The result enum has two variants representing a correct value and an Error.
Here, we define a function divide that performs division. It returns a Result enum to indicate success or failure. The divide function takes two parameters: dividend and divisor, both of type i32. It returns a Result<i32, String>. It can be Ok on success i.e (the result of the division). Otherwise it returns Err(String) if an error occurs i.e(like division by zero). Save the file. |
| Run the code and see the output
It displays 5 as the result of the division. | |
| Change the parameters in the divide function as (10,0).
Save the program and run it again. It displays the error message.
| |
| This brings us to the end of this tutorial.
Let us summarize.
| |
In this tutorial, we learn about
| |
| Thank You | Thanks for joining. |