TryFrom and TryInto

RustRustBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we explore the usage of TryFrom and TryInto in Rust, which are generic traits used for fallible conversions between types and return Result types. We provide an example code snippet that demonstrates the implementation of TryFrom for converting an i32 into a custom EvenNumber struct, and then showcase how to use TryFrom and TryInto to perform the conversion and handle the possible errors.

Note: If the lab does not specify a file name, you can use any file name you want. For example, you can use main.rs, compile and run it with rustc main.rs && ./main.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL rust(("`Rust`")) -.-> rust/BasicConceptsGroup(["`Basic Concepts`"]) rust(("`Rust`")) -.-> rust/DataTypesGroup(["`Data Types`"]) rust(("`Rust`")) -.-> rust/FunctionsandClosuresGroup(["`Functions and Closures`"]) rust(("`Rust`")) -.-> rust/DataStructuresandEnumsGroup(["`Data Structures and Enums`"]) rust(("`Rust`")) -.-> rust/AdvancedTopicsGroup(["`Advanced Topics`"]) rust/BasicConceptsGroup -.-> rust/variable_declarations("`Variable Declarations`") rust/DataTypesGroup -.-> rust/integer_types("`Integer Types`") rust/FunctionsandClosuresGroup -.-> rust/function_syntax("`Function Syntax`") rust/FunctionsandClosuresGroup -.-> rust/expressions_statements("`Expressions and Statements`") rust/DataStructuresandEnumsGroup -.-> rust/method_syntax("`Method Syntax`") rust/AdvancedTopicsGroup -.-> rust/traits("`Traits`") rust/AdvancedTopicsGroup -.-> rust/operator_overloading("`Traits for Operator Overloading`") subgraph Lab Skills rust/variable_declarations -.-> lab-99300{{"`TryFrom and TryInto`"}} rust/integer_types -.-> lab-99300{{"`TryFrom and TryInto`"}} rust/function_syntax -.-> lab-99300{{"`TryFrom and TryInto`"}} rust/expressions_statements -.-> lab-99300{{"`TryFrom and TryInto`"}} rust/method_syntax -.-> lab-99300{{"`TryFrom and TryInto`"}} rust/traits -.-> lab-99300{{"`TryFrom and TryInto`"}} rust/operator_overloading -.-> lab-99300{{"`TryFrom and TryInto`"}} end

TryFrom and TryInto

Similar to From and Into, [TryFrom] and [TryInto] are generic traits for converting between types. Unlike From/Into, the TryFrom/TryInto traits are used for fallible conversions, and as such, return [Result]s.

use std::convert::TryFrom;
use std::convert::TryInto;

#[derive(Debug, PartialEq)]
struct EvenNumber(i32);

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

    fn try_from(value: i32) -> Result<Self, Self::Error> {
        if value % 2 == 0 {
            Ok(EvenNumber(value))
        } else {
            Err(())
        }
    }
}

fn main() {
    // TryFrom

    assert_eq!(EvenNumber::try_from(8), Ok(EvenNumber(8)));
    assert_eq!(EvenNumber::try_from(5), Err(()));

    // TryInto

    let result: Result<EvenNumber, ()> = 8i32.try_into();
    assert_eq!(result, Ok(EvenNumber(8)));
    let result: Result<EvenNumber, ()> = 5i32.try_into();
    assert_eq!(result, Err(()));
}

Summary

Congratulations! You have completed the TryFrom and TryInto lab. You can practice more labs in LabEx to improve your skills.

Other Rust Tutorials you may like