liveBook · Manning

From trait

As explained in Rust Servers, Services, and Apps

From is the Rust standard-library trait for defining infallible conversions from one type into another.

`From` defines a conversion from one Rust type to another. Implement `From<Source> for Destination` with a `from` method when the conversion can return a destination value without a conversion error. Callers can then use `.into()` where the destination type is known. In an HTTP server, this keeps conversions close to the types they produce. section 2.3.1 section 6.2.1

impl From<&str> for Method {
    fn from(s: &str) -> Method {
        match s {
            "GET" => Method::Get,
            "POST" => Method::Post,
            _ => Method::Uninitialized,
        }
    }
}

The method conversion maps request-line strings to enum variants. Unsupported strings produce `Uninitialized` rather than a conversion error. section 2.3.1

Parse a request line

In `http/src/httprequest.rs`, `process_req_line` splits the request line into method, resource, and version. Its return tuple uses `method.into()` and `version.into()` to obtain `Method` and `Version` values. A unit test checks that `let m: Method = "GET".into()` equals `Method::Get`; another checks `"HTTP/1.1"` against `Version::V1_1`. `From<String> for HttpRequest` extends the pattern to an entire incoming request. section 2.3.1

The direction reverses for outgoing messages. `From<HttpResponse<'a>> for String` formats the status line, headers, content length, and body as an HTTP response message. `send_response` obtains that string with `String::from(res)` before writing it to the stream. A unit test compares a converted 404 response with the expected wire-format string. section 2.3.2

Listing 2.15 Code to serialize a Rust struct into an HTTP response message
impl<'a> From<HttpResponse<'a>> for String {
    fn from(res: HttpResponse) -> String {
        let res1 = res.clone();
        format!(
            "{} {} {}\r\n{}Content-Length: {}\r\n\r\n{}",
            &res1.version(),
            &res1.status_code(),
            &res1.status_text(),
            &res1.headers(),
            &res.body.unwrap().len(),
            &res1.body()
        )
    }
}

The response conversion assembles the fields into a message string, making the serialization boundary explicit. section 2.3.2

Conversions also connect application layers. For custom error handling, implement `From` conversions from distinct error types into one application error enum; implement Actix Web’s `ResponseError` on that enum to turn returned errors into HTTP responses. For course handlers, `From<web::Json<CreateCourse>> for CreateCourse` copies fields from a deserialized JSON wrapper into the input model. A corresponding `TryFrom` implementation returns `Result<Self, EzyTutorError>` when conversion may need an error path. section 5.3 section 5.7 section 6.2.1

impl From<web::Json<CreateCourse>> for CreateCourse {
 
    fn from(new_course: web::Json<CreateCourse>) -> Self {
        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,
        }
    }
}

The course-model implementation shows a field-by-field conversion from Actix Web’s JSON wrapper to the application input type. section 6.2.1

How Rust Servers, Services, and Apps covers it

How deep it goes
Works through concrete From implementations and unit tests, then outlines error conversion without showing its implementation.
Examples
Tests GET and HTTP/1.1 conversions, serializes a 404 response, and unwraps an Actix Web JSON input model.
What you can do after
Build it from scratch for request parsing and response serialization; apply it in Actix Web model and error workflows.
How it connects
Links HTTP parsing, HTTP serialization, custom error types, ResponseError, and TryFrom.

Also explained in

Compare how 4 books explain From trait →

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.