CH 6. Enums and Pattern Matching Flashcards
What is an enum in Rust?
An enum, short for enumeration, is a custom data type that allows you to define a type by enumerating its possible values.
How do you define an enum in Rust?
You define an enum using the enum keyword followed by the name of the enum and a list of its variants. For example:
enum Coins {
penny,
nickel,
dime,
quarter
}
What are the two types of enums in Rust?
Rust has two types of enums: those with named variants and those with unnamed variants (also known as unit-like or tuple-like). For example:
// named variants
enum Color {
Red,
Green,
Blue,
}
// Unnamed variants
enum Fruit {
Apple(String),
Banana(String),
Orange(String),
}
How do you use the match expression in Rust?
The match expression allows you to compare a value against a series of patterns and execute code based on the matched pattern.
What is exhaustive pattern matching?
Exhaustive pattern matching ensures that every possible case is handled in the match expression, leaving no unmatched patterns.
What is the purpose of the _ wildcard pattern in Rust?
The _ wildcard pattern is used as a catch-all for cases that are not explicitly defined in the match expression.
What is the if let expression in Rust?
The if let expression provides a more concise way to handle a single pattern match and execute code if the pattern matches.
What is the purpose of the Option enum in Rust?
The Option enum represents a value that can either be Some(value) or None, providing a way to handle optional values and potential absence of data.
What is the Result enum used for in Rust?
The Result enum is similar to Option but is typically used to handle operations that may produce an error. It can have two variants: Ok(value) or Err(error).
How can you bind values to variables within a pattern match?
By using the @ symbol followed by a pattern, you can bind the matched value to a variable for further use within the corresponding code block.