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:
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:
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.
