Open In App

Rust – TryFrom and TryInto Traits

Last Updated : 02 Oct, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

TryFrom and TryInto Traits in Rust are generic traits in Rust that are used for conversion between types. These traits are used for fallible conversions i.e. conversions, where a  normal iterator is wrapped by a fallible iterator and Result Enum, is returned. Result enum has two possible values => Ok (success) and Err (error).

TryFrom trait is used for safe conversions of data and in most situations it lets the programmer decides on situations when there is a data overflow and the programmer could handle that situation. 

Syntax:

//TryFrom Trait example

pub trait TryFrom<T>: Sized {
  type Error;
  fn try_from_function(value: T) -> Result<Self, Self::Error>;
}

Example 1:

Rust




# Rust program for TryFrom
#![allow(unused)]
    fn main() 
{
    struct GFG(i32);
  
    impl TryFrom<i32> for GFG
  {
    type Error = &'static str;
  
    fn try_from_func(value: i32) 
    -> Result<Self, Self::Error> 
      {
        if value >= 100 
        {
            Err("Accepts Value greater than 100")
        
        else 
        {
            Ok(GFG(value))
        }
    }
}


Explanation:

In this example, we define a struct GFG and initialize with an i32 type. Now, we implement the TryFrom<i32> trait for the GFG struct and declare the type Error as ‘static str’ i.e. the error type of the string. Now, we create a function ‘try_from_func’ from where we put an if else condition that if the value of the number is greater than 100 then the code will run else it throws an error statement (“Accepts value greater than 100”).

TryInto Traits:

Syntax:

//TryInto Trait example

pub trait TryInto<T>: Sized {
  type Error;
  fn try_into_func(self) -> Result<T, Self::Error>;
}

Example 2:

Rust




let smaller_number: i32 = greater_number.try_into().unwrap_or_else(|_|{
    if greater_number >= 0 {
        i32::MAX
    } else {
        i32::MIN
    }
});


Explanation: 

Here, for a negative scenario handling a negative case, we have used the unwrap_or_else() method. We have declared a variable smaller_number and then assigned it to a greater_number.method(). The try_into() method outputs a Result for us to choose how we handle the scenario in case a number overflows or is out of range and what we can do to fit it in the data type.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads