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
