Rust: Enum and int – int to enum

Background

In this quick post, we will cover how to move between enums and integers in Rust.

We will go from int to enum.

BTW, moving from enum to ints is a relatively more straight forward operation.

The latter can be accomplished by employing the cast operator.

 

Lineage

  1. Rust:- Enums
    Published:- 2023-April-11th
    Link

Translate Array Elements To Enum

Outline

  1. Choices
    • Choice -01
      • getArrayElementUsingEnumValuesEqualityCheck
        • Function
          • cast enum to integer ( i32 )
    • Choice -02 ( try_into )
      • getArrayElementsUsingTryInto
        • Function
          • Syntax
            • let mut [variable]:Result<Enum, ()>;
            • <i32 as TryInto<Enum>>::try_into ( int );
          • Sample
            • let mut season_context:Result<Season, ()>;
            • <i32 as TryInto<Season>>::try_into ( array_element_value );
    • Choice -03 ( try_from )
      • getArrayElementsUsingTryFrom
        • Function
          • Syntax
            • let mut [variable]:Result<Enum, ()>;
            • <Enum>::try_from(array_element_value);
          • Sample
            • let mut season_context:Result<Season, ()>;
            • season_context = Season::try_from ( array_element_value );

Enum Values Check

Function:- getArrayElementUsingEnumValuesEqualityCheck

Outline

  1. Declare Variables
    • let mut i:u16;
    • let mut array_element_value:i32;
    • let mut season_context:Result<Season, Box<dyn Error>>;
  2. Iterate array elements
    • array_element in array_of_seasons.iter()
      • Get value that pointer is pointing to
        • array_element_value = *array_element;

Function:- fetchSeason

Outline

  1. Declare Function
    • fn fetchSeason(value:i32) -> Result<Season, Box<dyn Error>>
  2. Declare Variables
    • let result:Season;
  3. Conpare value (int) to seasons
    • if value == Season::Winter as i32
      • set result = Season::Winter;
    • else if value == Season::Spring as i32
      • set result = Season::Spring;
    • else if value == Season::Summer as i32
      • set result = Season::Summer;
    • else if value == Season::Autum as i32
      • set result = Season::Autumn;
    • else raise error
      • return Err(“Error Unexpected argument (value)”.into());
  4. Return Success
    • return Ok(result);

Code


fn getArrayElementUsingEnumValuesEqualityCheck()
{
    
    /*
      Declare array pointer
    */
    let mut i:u16;

    let mut array_element_value:i32;

    /*
        Declare function return variable
    */
    let mut season_context:Result<Season, Box<dyn Error>>;
    
    println!("Function:- getArrayElementUsingEnumValuesEqualityCheck");
    println!("");
    
    /*
        Iterate array
    */
    i =0;
    for array_element in array_of_seasons.iter()
    {
      
      //move array pointer
      i = i + 1;
      
      //get value that pointer is pointing to
      array_element_value = *array_element;
      
      //get array element as enum
      season_context = fetchSeason
                       (
                            array_element_value
                       );
      
      
      //print array element to console
      println!
      (
          "\tElement {} is {} (int) | {:?} ( enum )"
         , i 
         , array_element
         , season_context
      );
    
    }
    
    
    println!("");
    println!("");
    
}

Generic Trait – TryInto

Function:- getArrayElementsUsingTryInto

Outline

  1. Declare Variables
    • let mut i:u16;
    • let mut season_context:Result<Season, ()>;
  2. Iterate array elements
    • array_element in array_of_seasons.iter()
      • Get value that pointer is pointing to
        • array_element_value = *array_element;
    • try to convert int into enum value, using tryinto
      
      //try to convert int into enum value
      //using tryinto
      
      season_context 
              = <i32 as TryInto<Season>>::try_into
                          (
                              array_element_value
                          );
            
      

Code


fn getArrayElementsUsingTryInto()
{
    
    /*
      Declare array pointer
    */
    let mut i:u16;

    /*
        Declare function return variable
    */
    let mut season_context:Result<Season, ()>;
    
    println!("Function:- getArrayElementsUsingTryInto");
    println!("");
    
    /*
        Iterate array
    */
    i =0;
    for array_element in array_of_seasons.iter()
    {
      
      //move array pointer
      i = i + 1;
      
      //get value that pointer is pointing to
      let array_element_value:i32 = *array_element;
     
      //try to convert int into enum value
      //using tryinto
      season_context 
        = <i32 as TryInto<Season>>::try_into
                    (
                        array_element_value
                    );
      
      //print array element to console
      println!
      (
          "\tElement {} is {} (int) | {:?} ( enum )"
         , i 
         , array_element
         , season_context
      );
    
    }
    
    
    println!("");
    println!("");
    
}


Generic Trait – TryFrom

Implement:- TryForm<i32>for Season

Function:- TryForm<i32> for Season

Outline
  1. Declare Variables
  2. Implement Season::try_form
    • Declare Function
      • try_from(v: i32) -> Result<Self, Self::Error>
    • Match variable ( v)
      • If v == Season::Winter as i32
        • return OK(Season::Winter )
      • If v == Season::Spring as i32
        • return OK(Season::Spring )
      • If v == Season::Summer as i32
        • return OK(Season::Summer )
      • If v == Season::Autumn as i32
        • return OK(Season::Autumn )
      • Else
        • return Err(())

Code

impl TryFrom<i32> for Season
{
    type Error = ();

    fn try_from(v: i32) -> Result<Self, Self::Error> 
    {
        match v 
        {
            x if x == Season::Winter as i32 => Ok(Season::Winter),
            x if x == Season::Spring as i32 => Ok(Season::Spring),
            x if x == Season::Summer as i32 => Ok(Season::Summer),
            x if x == Season::Autumn as i32 => Ok(Season::Autumn),
            _ => Err(()),
        }
    }
}

Function:- getArrayElementsUsingTryFrom

Outline

  1. Declare Variables
    • let mut i:u16;
    • let mut season_context:Result<Season, ()>;
  2. Iterate array elements
    • array_element in array_of_seasons.iter()
      • Get value that pointer is pointing to
        • array_element_value = *array_element;
    • try to convert int into enum value, using tryfrom
      
       //attempt to get season enum from int
       //use try_from
       //implemented earlier
       season_context = Season::try_from
                              (
                                  array_element_value
                              );  
          
      

Code


fn getArrayElementsUsingTryFrom()
{
    
    /*
      Declare array pointer
    */
    let mut i:u16;
    
    /*
        declare value of array element
    */
    let mut array_element_value:i32;

    /*
        Declare function return variable
    */
    let mut season_context:Result<Season, ()>;
    
    println!("Function:- getArrayElementsUsingTryFrom");
    println!("");
    
    /*
        Iterate array
    */
    i =0;
    for array_element in array_of_seasons.iter()
    {
      
      //move array pointer
      i = i + 1;
      
      //get value that pointer is pointing to
      array_element_value = *array_element;
     
      //attempt to get season enum from int
      //use try_from
      //implemented earlier
      season_context = Season::try_from
                        (
                            array_element_value
                        );
      
      //print array element to console
      println!
      (
          "\tElement {} is {} (int) | {:?} ( enum )"
         , i 
         , array_element
         , season_context
      );
    
    }
    
    
    println!("");
    println!("");
    
}

Full Code


/*
    Import Traits
*/
use std::error::Error;
use std::convert::TryFrom;
use std::convert::TryInto;

/*
    Declare array of seasons
*/
const array_of_seasons:[i32;5] = [
                                     1
                                    ,2
                                    ,3
                                    ,4
                                    ,5
                                ];
    
/*
   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 = 1
    
    , Spring = 2
    
    , Summer = 3
    
    , Autumn = 4
    
}


/*
    Attempt to convert u16 to Enum Season
*/

/*
    How do I match enum values with an integer?
    https://stackoverflow.com/questions/28028854/how-do-i-match-enum-values-with-an-integer?rq=1
*/

impl TryFrom<i32> for Season
{
    type Error = ();

    fn try_from(v: i32) -> Result<Self, Self::Error> 
    {
        match v 
        {
            x if x == Season::Winter as i32 => Ok(Season::Winter),
            x if x == Season::Spring as i32 => Ok(Season::Spring),
            x if x == Season::Summer as i32 => Ok(Season::Summer),
            x if x == Season::Autumn as i32 => Ok(Season::Autumn),
            _ => Err(()),
        }
    }
}


/*
    How do I match enum values with an integer?
    https://stackoverflow.com/questions/58393250/returning-error-message-to-function-expecting-boxdyn-error
*/
fn fetchSeason
(
    value:i32
) -> Result<Season, Box<dyn Error>>
{

    //declare type Error
    type Error = ();

    //declare result as season
    let result:Season;
    
    if value == Season::Winter as i32
    {
    
        result = Season::Winter;
        
    }
    else if value == Season::Spring as i32
    {
    
        result = Season::Spring;
        
    }
    else if value == Season::Summer as i32
    {
    
        result = Season::Summer;
        
    }
    else if value == Season::Autumn as i32
    {
    
        result = Season::Autumn;
        
    }
    else
    {
      
      //raise informative error
      //convert string to err type
       return Err
            (
                "Error Unexpected argument (value)".into()
            );
    }
    
    //return OK and season (as result)
    return Ok(result);
    
}


fn getArrayElementUsingEnumValuesEqualityCheck()
{
    
    /*
      Declare array pointer
    */
    let mut i:u16;

    let mut array_element_value:i32;

    /*
        Declare function return variable
    */
    let mut season_context:Result<Season, Box<dyn Error>>;
    
    println!("Function:- getArrayElementUsingEnumValuesEqualityCheck");
    println!("");
    
    /*
        Iterate array
    */
    i =0;
    for array_element in array_of_seasons.iter()
    {
      
      //move array pointer
      i = i + 1;
      
      //get value that pointer is pointing to
      array_element_value = *array_element;
      
      //get array element as enum
      season_context = fetchSeason
                       (
                            array_element_value
                       );
      
      
      //print array element to console
      println!
      (
          "\tElement {} is {} (int) | {:?} ( enum )"
         , i 
         , array_element
         , season_context
      );
    
    }
    
    
    println!("");
    println!("");
    
}

fn getArrayElementsUsingTryInto()
{
    
    /*
      Declare array pointer
    */
    let mut i:u16;

    /*
        Declare function return variable
    */
    let mut season_context:Result<Season, ()>;
    
    println!("Function:- getArrayElementsUsingTryInto");
    println!("");
    
    /*
        Iterate array
    */
    i =0;
    for array_element in array_of_seasons.iter()
    {
      
      //move array pointer
      i = i + 1;
      
      //get value that pointer is pointing to
      let array_element_value:i32 = *array_element;
     
      //try to convert int into enum value
      //using tryinto
      season_context 
        = <i32 as TryInto<Season>>::try_into
                    (
                        array_element_value
                    );
      
      //print array element to console
      println!
      (
          "\tElement {} is {} (int) | {:?} ( enum )"
         , i 
         , array_element
         , season_context
      );
    
    }
    
    
    println!("");
    println!("");
    
}



fn getArrayElementsUsingTryFrom()
{
    
    /*
      Declare array pointer
    */
    let mut i:u16;
    
    /*
        declare value of array element
    */
    let mut array_element_value:i32;

    /*
        Declare function return variable
    */
    let mut season_context:Result<Season, ()>;
    
    println!("Function:- getArrayElementsUsingTryFrom");
    println!("");
    
    /*
        Iterate array
    */
    i =0;
    for array_element in array_of_seasons.iter()
    {
      
      //move array pointer
      i = i + 1;
      
      //get value that pointer is pointing to
      array_element_value = *array_element;
     
      //attempt to get season enum from int
      //use try_from
      //implemented earlier
      season_context = Season::try_from
                        (
                            array_element_value
                        );
      
      //print array element to console
      println!
      (
          "\tElement {} is {} (int) | {:?} ( enum )"
         , i 
         , array_element
         , season_context
      );
    
    }
    
    
    println!("");
    println!("");
    
}

fn main() 
{

    getArrayElementUsingEnumValuesEqualityCheck();
    
    getArrayElementsUsingTryInto();
    
    getArrayElementsUsingTryFrom();
    
}



 

Online Code Sharing

OnlineGDB

  1. rustEnumAsIntegerArray
    Link

 

Source Code Control

GitLab

  1. rustEnum
    • rustEnumAsIntegerArray.rs
      Link

 

Referenced Work

  1. Stack Overflow
    • How do I match enum values with an integer?
      Link
    • Returning error message to function expecting ‘Box<dyn Error>’
      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