Rust:- Enums

Background

Quick introduction to enums in Rust.

 

What is an enum?

Enums allows us to group well known attributes or states into a distinct category.

Defining the well known values as an enum helps us in the following ways:-

  1. Consistency
    • Consistent Name
    • Consistent Value
  2. Abstract
    • Illuminate and Codify the real world
  3. State Machine
    • More precisely describe a state machine

 

Code

Code Snippet


/*
   Declare enum Season
   
        print using debug symbols
        ------------------------
        #[derive(Debug)]
        
        
        compare enum values against other enum values
        ---------------------------------------------
        #[derive(PartialEq, Eq)]
        
*/
#[derive(Debug)]
#[derive(PartialEq, Eq)]
enum Season
{

    Winter,
    
    Spring,
    
    Summer,
    
    Autumn,
    
}

fn main() 
{

    /*
        Declare variables
    */
    let mut season_current:Season;
    let mut season_is_autumn:bool;
    
    /*
        Set current season to spring
    */
    
    season_current = Season::Spring;
    
    /*
        Print current season as enum
    */
    println!(   
                 "\tSeason:- {:?}"
               , season_current
            );  
            
    /*
        Print current season as int ( unsigned )
    */
    println!(   
                 "\tSeason:- {:?}"
               , season_current as u8
            );  
                        
    
    /*
        Set current season to summer
    */ 
    season_current = Season::Summer;
    
    /*
        Is current season autumn
    */     
    season_is_autumn = season_current == Season::Autumn;
    
    /*
        Print result of comparing current season to Autumn
    */      
    println!( 
                    "\tIs Current Season ( {:#?} ), {:#?}:- {:#?}"
                  , season_current
                  , Season::Autumn
                  , season_is_autumn
            );              
}

Output

Output – Image

Output – Text


     Season:- Spring
     Season:- 1
     Is Current Season ( Summer ), Autumn:- false

Error Messages

error[E0277]: [enum-type] doesn’t implement `Debug`

 

If the enum type does not have “#[derive(Debug)]”, attempting to use {:?} in a println! statement will trigger an error.

 

BTW, {:?} is a debug symbol.

Error Message


error[E0277]: `Season` doesn't implement `Debug`
  --> main.rs:49:18
   |
49 |                , season_current
   |                  ^^^^^^^^^^^^^^ `Season` cannot be formatted using `{:?}`
   |
   = help: the trait `Debug` is not implemented for `Season`
   = note: add `#[derive(Debug)]` to `Season` or manually `impl Debug for Season`
   = note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
help: consider annotating `Season` with `#[derive(Debug)]`
   |
16 | #[derive(Debug)]
   |

Source Code Statement


    println!(   
                 "\tSeason:- {:?}"
               , season_current
            );
	

Remediation

To furnish the enum class with the Debug trait utilize:-


#[derive(Debug)]

 

 

error[E0369]: binary operation `==` cannot be applied to type `[enum-type]`

If the enum declaration is missing “#[derive(PartialEq, Eq)]”, attempting to compare enum values will raise a compilation error.

Error Message



error[E0369]: binary operation `==` cannot be applied to type `Season`
  --> main.rs:69:39
   |
69 |     season_is_autumn = season_current == Season::Autumn;
   |                        -------------- ^^ -------------- Season
   |                        |
   |                        Season
   |
note: an implementation of `PartialEq<_>` might be missing for `Season`
  --> main.rs:16:1
   |
16 | enum Season
   | ^^^^^^^^^^^ must implement `PartialEq<_>`
help: consider annotating `Season` with `#[derive(PartialEq)]`
   |
16 | #[derive(PartialEq)]
   |
error: aborting due to previous error
For more information about this error, try `rustc --explain E0369`.

 

Source Code Statement


    season_is_autumn = season_current == Season::Autumn;
	

 

Remediation

To allow support equality checks on an enum type, provide the PartialEq trait:-


#[derive(PartialEq, Eq)]

Online Code IDE

OnlineGDB

  1. rustenumseason
    Link

 

Source Code Control

GitLab

  1. rustenumseason
    Link

 

References

  1. rust-lang.org
    • Error code E0277
      You tried to use a type which doesn’t implement some trait in a place which expected that trait.
      Link
    • Error code E0369
      A binary operation was attempted on a type which doesn’t support it.
      Link
  2. StackOverflow
    • How do I get the integer value of an enum?
      Link
    • How do I match enum values with an integer?
      Link

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s