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
- Rust:- Enums
Published:- 2023-April-11th
Link
Translate Array Elements To Enum
Outline
- Choices
- Choice -01
- getArrayElementUsingEnumValuesEqualityCheck
- Function
- cast enum to integer ( i32 )
- Function
- getArrayElementUsingEnumValuesEqualityCheck
- 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 );
- Syntax
- Function
- getArrayElementsUsingTryInto
- 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 );
- Syntax
- Function
- getArrayElementsUsingTryFrom
- Choice -01
Enum Values Check
Function:- getArrayElementUsingEnumValuesEqualityCheck
Outline
- Declare Variables
- let mut i:u16;
- let mut array_element_value:i32;
- let mut season_context:Result<Season, Box<dyn Error>>;
- Iterate array elements
- array_element in array_of_seasons.iter()
- Get value that pointer is pointing to
- array_element_value = *array_element;
- Get value that pointer is pointing to
- array_element in array_of_seasons.iter()
Function:- fetchSeason
Outline
- Declare Function
- fn fetchSeason(value:i32) -> Result<Season, Box<dyn Error>>
- Declare Variables
- let result:Season;
- 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());
- if value == Season::Winter as i32
- 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
- Declare Variables
- let mut i:u16;
- let mut season_context:Result<Season, ()>;
- Iterate array elements
- array_element in array_of_seasons.iter()
- Get value that pointer is pointing to
- array_element_value = *array_element;
- Get value that pointer is pointing to
- 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 );
- array_element in array_of_seasons.iter()
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
- Declare Variables
- 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(())
- If v == Season::Winter as i32
- Declare Function
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
- Declare Variables
- let mut i:u16;
- let mut season_context:Result<Season, ()>;
- Iterate array elements
- array_element in array_of_seasons.iter()
- Get value that pointer is pointing to
- array_element_value = *array_element;
- Get value that pointer is pointing to
- 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 );
- array_element in array_of_seasons.iter()
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
- rustEnumAsIntegerArray
Link
Source Code Control
GitLab
- rustEnum
- rustEnumAsIntegerArray.rs
Link
- rustEnumAsIntegerArray.rs