Rust - Enums Flashcards
Describe #[derive(Debug)] in enums
[derive(Debug)] is an attribute in Rust that automatically generates implementations of the Debug trait for enums.
This implementation allows enums and their variants to be printed in a developer-friendly format using println!(“”, enum_value).
It saves developers from manually implementing the Debug trait,
Give example of implmenting enums
[derive(Debug)]
enum GenderCategory {
Male,Female
}
fn main() {
let male = GenderCategory::Male;
let female = GenderCategory::Female;
println!(““,male);
println!(““,female);
}
How would you use structs and enum
[derive(Debug)]
enum GenderCategory {
Male,Female
}
// The derive
attribute automatically creates the implementation
// required to make this struct
printable with fmt::Debug
.
#[derive(Debug)]
struct Person {
name:String,
gender:GenderCategory
}
fn main() {
let p1 = Person {
name:String::from(“Mohtashim”),
gender:GenderCategory::Male
};
let p2 = Person {
name:String::from(“Amy”),
gender:GenderCategory::Female
};
println!(““,p1);
println!(““,p2);
}
What is Option Enum
Option is a predefined enum in the Rust standard library. This enum has two values − Some(data) and None.
What is the syntax
enum Option<T>{
Some(T) // used to return a value
None // used to return null , as rust doensnt support the null keyworkd
}</T>
Give an exameple ofthe use of Option
fn main() {
let result = is_even(3);
println!(““,result);
println!(““,is_even(30));
}
fn is_even(no:i32)->Option<bool> {
if no%2 == 0 {
Some(true)
} else {
None</bool>
Use match statement in enum
enum CarType{
Hatch,
Sedan,
Mercedez
}
fn print_size(car:CarType){
match car{
CarType::Hatch => {
println!(“Small sized car”);
},
CarType::Sedan => {
println!(“medium sized car”);
},
CarType::Mercedez =>{
println!(“Large sized Sports Utility car”);
}
}
}
fn main(){
print_size(CarType::SUV);
print_size(CarType::Hatch);
print_size(CarType::Sedan);
}
How to do match with Option
fn is_even(no:i32)->Option<bool> {
if no%2 == 0 {
Some(true)
} else {
None
}
}</bool>
fn main(){
match is_even(5) {
Some(data) => {
if data==true {
println!(“Even no”);
}
},
None => {
println!(“not even”);
}
}
}