The Rust Programming Language — Pattern Matching — Type Parameters
Every coin has two sides — good and bad. Similarly, every programming language does have to deal with something that is defined and undefined or null. Rust particularly does not shine well when it comes to handling undefined or null. Rust will panic and start throwing an error when it comes across something that is undefined or null.
For these edge cases where things do go bad, Rust has given us Type Parameters and twoenum types, Option and Result. These two enum types are built into Rust language and can be used across the language and packages.
Option is used to handle the cases where there are chances or receiving undefined or null.
Result is used to handle the cases where there are chances getting Success and Error, for e.g. an asynchronous task.
Let’s see the definition of Option and Result in the below snippets:
enum Option<T> {
None,
Some(T),
}enum Result<T, E> {
Ok(T),
Err(E),
}Observations:
- These enums
OptionsandResultare part of the Rust Language itself. - It passes types using
Tinside the<>brackets, just like generics in TypeScript. - This
Tis known as Type Parameter and can be passed along Optionhas 2variants,NoneandSome<T>.Nonemeans undefined/empty/null andSome<T>means some elements of typeT.Resulthas 2variants,Ok<T>andErr<E>.Okis for success message andErris for error message.
Since Option and Result are built in to the system, you do not need the namespace syntax, i.e. ::, for accessing the None or Some and Ok or Error. You can directly use them. Lets have a look at below code snippet:
fn main() {
let mut my_string: String = "hello world".to_string();
let mut email_string: String = "[email protected]".to_string();
// let last_char: char = my_string.pop();
let last_char: Option<char> = my_string.pop();
let email: Option<String> = Some(email_string);
let empty_string: Option<String> = None;
let success: Result<String, String> = Ok("Success".to_string());
let error: Result<String, String> = Err("Error".to_string());
}Observations:
Option<char>is used to store the result coming frommy_string.pop()which can either be a character orundefinedornullif string is empty.Some(email_string)is used to represent somecharfromemail_string- Notice that
Someis not used asOption::Some(), i.e. with namespace, it is directly used. - Similarly
OkandErrare used without a namespace.
Using Type Parameters, we can build a flexible types and prevent Rust compiler from panicking when it encounters undefined and null.
I hope you liked this article about Type Parameters. Please share your feedback in the comments.
You can subscribe to my newsletter about The Rust Programming Language here. You can read about all the articles in this series here.






