Rust - Enums Flashcards

1
Q

Describe #[derive(Debug)] in enums

A

[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,

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Give example of implmenting enums

A

[derive(Debug)]

enum GenderCategory {
Male,Female
}
fn main() {
let male = GenderCategory::Male;
let female = GenderCategory::Female;

println!(““,male);
println!(““,female);
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How would you use structs and enum

A

[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);
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is Option Enum

A

Option is a predefined enum in the Rust standard library. This enum has two values − Some(data) and None.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is the syntax

A

enum Option<T>{
Some(T) // used to return a value
None // used to return null , as rust doensnt support the null keyworkd
}</T>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Give an exameple ofthe use of Option

A

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>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Use match statement in enum

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How to do match with Option

A

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”);
}
}
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q
A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly