Enums in Rust Programing

Rust ProgrammingServer Side ProgrammingProgramming

Also referred to as enumerations, enums are very useful in certain cases. In Rust, we use enums, as they allow us to define a type that may be one of a few different variants.

Enumerations are declared with the keyword enum.

Example

 Live Demo

#![allow(unused)]
#[derive(Debug)]
enum Animal {
   Dog,
   Cat,
}
fn main() {
   let mut b : Animal = Animal::Dog;
   b = Animal::Cat;
   println!("{:?}",b);
}

Output

Cat

Zero-variant Enums

Enums in Rust can also have zero variants, hence the name Zero-variant enums. Since they do not have any valid values, they cannot be instantiated.

Zero-variant enums are equivalent to the never type in Rust.

Example

 Live Demo

#![allow(unused)]
#[derive(Debug)]
enum ZeroVariantEnum {}
fn main() {
   let x: ZeroVariantEnum = panic!();
   println!("{:?}",x);
}

Output

thread 'main' panicked at 'explicit panic', src/main.rs:7:30
raja
Published on 03-Apr-2021 12:45:21
Advertisements