0
0
Rustprogramming~5 mins

Generic enums in Rust - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a generic enum in Rust?
A generic enum in Rust is an enum that can hold different types specified by a generic parameter. It allows the enum to be flexible and work with various data types.
Click to reveal answer
beginner
How do you define a generic enum with one type parameter in Rust?
You add a type parameter inside angle brackets after the enum name, like <T>. For example: <br>
enum Option<T> {
    Some(T),
    None,
}
Click to reveal answer
intermediate
Why use generic enums instead of fixed-type enums?
Generic enums let you write one enum that works with many types, reducing code duplication and increasing flexibility. For example, Option<T> can hold any type T, not just one fixed type.
Click to reveal answer
intermediate
Can generic enums have multiple type parameters? Give an example.
Yes, generic enums can have multiple type parameters. Example:<br>
enum Result {
    Ok(T),
    Err(E),
}
This enum can hold a success value of type T or an error value of type E.
Click to reveal answer
beginner
How do you create an instance of a generic enum with a specific type?
You specify the type when you use the enum. For example:<br><pre>let x: Option<i32> = Option::Some(5);</pre> Here, Option is used with i32 as the type parameter.
Click to reveal answer
What does the <T> mean in enum Option<T>?
AIt declares a generic type parameter T for the enum.
BIt is a syntax error in Rust.
CIt means the enum only works with type T fixed as integer.
DIt is a lifetime parameter.
Which of these is a valid generic enum definition?
Aenum Result { Ok<T>, Err<E> }
Benum Result<T, E> { Ok(T), Err(E) }
Cenum Result<T> { Ok, Err }
Denum Result<T, E> { Ok, Err }
How do you create an Option holding a string "hello"?
AOption::Some("hello")
BOption::Some(hello)
COption::None("hello")
DOption::Some<String>
What is the benefit of using generic enums?
AThey restrict enums to only one data type.
BThey make enums slower.
CThey allow enums to work with multiple data types without rewriting code.
DThey are only used for error handling.
Can you use a generic enum without specifying the type parameter?
AOnly if the enum has no variants.
BYes, Rust assumes a default type.
CYes, generic enums do not require type parameters.
DNo, you must specify or let Rust infer the type.
Explain what a generic enum is and why it is useful in Rust.
Think about how enums can hold different types using generics.
You got /3 concepts.
    Write a simple generic enum with two variants and explain how to create an instance of it.
    Use something like Result<T, E> or Option<T>.
    You got /3 concepts.