Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to define an enum variant named Red.
Rust
enum Color {
[1],
Green,
Blue,
}Attempts:
3 left
💡 Hint
Common Mistakes
Using lowercase or all uppercase names for variants.
Adding prefixes like 'color' to variant names.
✗ Incorrect
Enum variants in Rust are usually written in PascalCase. Here,
Red is the correct variant name.2fill in blank
mediumComplete the code to create a variable c with the enum variant Color::Green.
Rust
enum Color {
Red,
Green,
Blue,
}
let c = [1];Attempts:
3 left
💡 Hint
Common Mistakes
Using dot notation instead of double colon.
Using lowercase variant names.
✗ Incorrect
To create a variable with an enum variant, use the syntax
EnumName::Variant. Here, Color::Green is correct.3fill in blank
hardFix the error in the match expression to correctly match the Color enum variants.
Rust
enum Color {
Red,
Green,
Blue,
}
let c = Color::Blue;
match c {
[1] => println!("It's red!"),
Color::Green => println!("It's green!"),
Color::Blue => println!("It's blue!"),
}Attempts:
3 left
💡 Hint
Common Mistakes
Using dot notation instead of double colon in match arms.
Using lowercase variant names.
✗ Incorrect
In match arms, enum variants can be matched with the full path using double colons, like
Color::Red.4fill in blank
hardFill both blanks to define an enum variant Rgb with three u8 values and create a variable color with that variant.
Rust
enum Color {
[1](u8, u8, u8),
Cmyk,
}
let color = Color::[2](255, 0, 0);Attempts:
3 left
💡 Hint
Common Mistakes
Using different names or cases between definition and usage.
Using lowercase variant names.
✗ Incorrect
The variant name must be the same in both definition and usage.
Rgb is the correct PascalCase variant name.5fill in blank
hardFill all three blanks to create a match expression that prints the RGB values from the Color::Rgb variant.
Rust
enum Color {
Rgb(u8, u8, u8),
Cmyk,
}
let color = Color::Rgb(10, 20, 30);
match color {
Color::Rgb([1], [2], [3]) => {
println!("Red: {}, Green: {}, Blue: {}", r, g, b);
},
_ => println!("Not an RGB color"),
}Attempts:
3 left
💡 Hint
Common Mistakes
Using variable names that don't match the print statement.
Using a single variable for all three values.
✗ Incorrect
The variables
r, g, and b are used to capture the RGB values in the match pattern.