liveBook · Manning

TryFrom

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

TryFrom is a Rust standard-library trait for conversions that may fail and therefore return a result indicating success or error.

Use Rust’s std::convert::TryFrom for a type conversion that may fail. Unlike a From conversion, a TryFrom conversion reports whether it succeeded or produced an error. Prefer From when the conversion is mathematically equivalent. section 5.5 section 5.8

A fixed-point conversion decision

A conversion from f64 to the fixed-point Q7 type uses From and clamps values outside its range: 10.0 becomes the same Q7 value as 1.0. If losing that information is unacceptable, treat out-of-range input as a possible failure and consider TryFrom instead. The Q7 example does not implement TryFrom. section 5.5

Listing 5.12 Converting from f64 to Q7
 impl From<f64> for Q7 {
     fn from (n: f64) -> Self {
         // assert!(n >= -1.0);
         // assert!(n <= 1.0);
         if n >= 1.0 {                     #1
             Q7(127)
         } else if n <= -1.0 {             #1
             Q7(-128)
         } else {
             Q7((n * 128.0) as i8)
         }
     }
 }
 
 impl From<Q7> for f64 {
     fn from(n: Q7) -> f64 {
         (n.0 as f64) * 2_f64.powf(-7.0)   #2
     }
 }

The From<f64> implementation shows where out-of-range inputs are clamped rather than rejected. section 5.5

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

How deep it goes
Defines when to prefer TryFrom but stops short of implementing it or working through its error handling.
Examples
Contrasts the recommendation with a Q7 From implementation that clamps out-of-range f64 inputs; provides no TryFrom example.
What you can do after
Evaluate/understand when a potentially failing conversion calls for TryFrom rather than From.
How it connects
Connects TryFrom to From, type conversion, and fixed-point number formats.

Also explained in

Compare how 3 books explain TryFrom →

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.