Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rust: Not explicitly saying `return` gives error: `match` arms have incompatible types

I am very new to Rust.

The following function:

async fn create(body: String) -> impl IntoResponse {

    let j = match serde_json::from_str::<CreationJSON>(&body) {
        Ok(j) => j,
        Err (_) => (
            StatusCode::UNPROCESSABLE_ENTITY,
            "body is invalid".to_string(),
        ),
    };
    println!("{:?}", j.record_stringified);

    (
        StatusCode::CREATED,
        "created".to_string(),
    )
}

gives error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

error[E0308]: `match` arms have incompatible types
   --> src/main.rs:128:20
    |
126 |       let j = match serde_json::from_str::<CreationJSON>(&body) {
    |               ------------------------------------------------- `match` arms have incompatible types
127 |           Ok(j) => j,
    |                    - this is found to be of type `CreationJSON`
128 |           Err (_) => (
    |  ____________________^
129 | |             StatusCode::UNPROCESSABLE_ENTITY,
130 | |             "body is invalid".to_string(),
131 | |         ),
    | |_________^ expected `CreationJSON`, found `(StatusCode, String)`
    |
    = note: expected struct `CreationJSON`
                found tuple `(axum::http::StatusCode, std::string::String)`

Screenshot:

enter image description here

However, if I add a "return" to the Err arm, then it works fine:

async fn create(body: String) -> impl IntoResponse {

    let j = match serde_json::from_str::<CreationJSON>(&body) {
        Ok(j) => j,
        Err (_) => return (
            StatusCode::UNPROCESSABLE_ENTITY,
            "body is invalid".to_string(),
        ),
    };
    println!("{:?}", j.record_stringified);

    (
        StatusCode::CREATED,
        "created".to_string(),
    )

}

Why do I need to add the return in the Err arm? I thought a function with no semi-colon was supposed to automatically return in Rust?

>Solution :

return returns from the function. If you don’t use the return keyword, then it’ll "return" from the statement. In your first example, you’re trying to assign the tuple to the variable j, while in the second you return from the function.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading