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
Options
andResult
are part of the Rust Language itself. - It passes types using
T
inside the<>
brackets, just like generics in TypeScript. - This
T
is known as Type…