liveBook · Manning

TryFrom

As explained in Rust Servers, Services, and Apps

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

TryFrom is a Rust standard-library trait for conversions that may fail. It returns Result<Self, Error>, allowing conversion faults to use the application's unified error type. section 6.2.1

In an Actix Web handler, incoming web::Json<CreateCourse> data can be converted into the regular CreateCourse struct. Implement try_from, declare EzyTutorError as the associated Error type, and return Ok for successful construction or an application error when processing fails. section 6.2.1

Converting an incoming course payload

use std::convert::TryFrom; impl TryFrom<web::Json<CreateCourse>> for CreateCourse { type Error = EzyTutorError; fn try_from(new_course: web::Json<CreateCourse>) -> Result<Self, Self::Error> { Ok(CreateCourse { tutor_id: new_course.tutor_id, course_name: new_course.course_name.clone(), course_description: new_course.course_description.clone(), course_format: new_course.course_format.clone(), course_structure: new_course.course_structure.clone(), course_level: new_course.course_level.clone(), course_duration: new_course.course_duration.clone(), course_language: new_course.course_language.clone(), course_price: new_course.course_price, }) } } This example has no anticipated failure conditions, so From is sufficient in practice; TryFrom demonstrates the fallible form. section 6.2.1

How Rust Servers, Services, and Apps covers it

How deep it goes
Defines try_from, Result, and an associated error type, but stops short of implementing a genuinely failing conversion.
Examples
Uses web::Json<CreateCourse> conversion and mentions string-to-integer conversion as a possible failure.
What it assumes
Assumes Rust structs, traits, Result, and Actix Web JSON types while demonstrating the associated error declaration.
What you can do after
Apply it via Rust's standard library to express fallible application-specific conversions with unified errors.
How it connects
Connects fallible conversion with From, Result, error handling, Actix Web, and request deserialization.

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 Servers, Services, and Apps. The section links point to the parts of the book it draws on.