liveBook · Manning

TryInto

As explained in Rust in Action: Systems programming concepts and techniques

TryInto is a Rust standard-library trait for fallible conversion of a value into a specified target type.

TryInto performs a fallible conversion into a specified target type. Unlike an unchecked as cast, it returns a Result, making conversion failure visible. section 2.3.3

Convert before comparing

Import std::convert::TryInto, then call try_into() on a u16 value. In the example, b.try_into().unwrap() produces an i32 so it can be compared with a. unwrap() extracts success but can crash if conversion fails; safer Result handling comes later. section 2.3.3

Listing 2.5 The try_into() method converts between types
 use std::convert::TryInto;    #1
 
 fn main() {
   let a: i32 = 10;
   let b: u16 = 100;
 
   let b_ = b.try_into()
             .unwrap();        #2
 
   if a < b_ {
     println!("Ten is less than one hundred.");
   }
 }

View the complete Rust listing showing the trait import, try_into() call, Result extraction, and comparison. section 2.3.3

How Rust in Action: Systems programming concepts and techniques covers it

How deep it goes
Defines the trait and demonstrates one conversion, while deferring full traits and safer Result handling.
Examples
Demonstrates converting a u16 value into i32 before comparing it with an i32 value.
What it assumes
Assumes basic Rust variables, numeric types, comparisons, imports, and method calls while introducing traits and Result.
What you can do after
Apply TryInto by importing its trait, calling try_into(), and handling the returned Result.
How it connects
Connects traits, Result, error handling, numeric types, type casts, and scope-based method availability.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Rust in Action: Systems programming concepts and techniques. The section links point to the parts of the book it draws on.