rustGet all enum values in Rust
In Rust, enum values can be accessed using the variants()
method. This method returns an iterator over all the variants of the enum. To get all the enum values, the iterator can be collected into a vector. The ## Code example below shows how to do this:
enum Color {
Red,
Green,
Blue,
}
fn main() {
let colors: Vec<Color> = Color::variants().collect();
println!("{:?}", colors);
}
The output of this code is:
[Red, Green, Blue]
The variants()
method returns an iterator over all the variants of the enum. This iterator is then collected into a vector, which is then printed out. The {:?}
format specifier is used to print out the vector in a readable format.
Helpful links
Related
More of Rust
- How to use non-capturing groups in Rust regex?
- How to match whitespace with a regex in Rust?
- How to split a string with Rust regex?
- How to build a Rust HashMap from an iterator?
- How do I copy a variable in Rust?
- How to cast pointer to usize in Rust
- How to use Unicode in a regex in Rust?
- How to use regex to match a double quote in Rust?
- How to get a capture group using Rust regex?
- How to match a URL with a regex in Rust?
See more codes...