代码之家  ›  专栏  ›  技术社区  ›  sudoExclamationExclamation

Rust:没有明确地说“return”会产生错误:“match”arm具有不兼容的类型

  •  1
  • sudoExclamationExclamation  · 技术社区  · 2 年前

    我对Rust很陌生。

    以下功能:

    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(),
        )
    }
    

    给出错误:

    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)`
    

    但是,如果我在 Err 手臂,那么它工作得很好:

    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(),
        )
    }
    

    为什么我需要添加 return 在中 犯错误 臂我以为一个没有分号的函数应该在Rust中自动返回?

    2 回复  |  直到 2 年前
        1
  •  1
  •   Ted Klein Bergman    2 年前

    return 从函数返回。如果您不使用 回来 关键字,则它将从语句中“返回”。在第一个示例中,您试图将元组分配给变量 j ,而在第二秒内,您从函数返回。

        2
  •  0
  •   user-id-14900042    2 年前

    请注意后一个代码编译的原因:在Rust中,每个arm的返回值类型必须在 type coercion 被调用。 return 语句的类型为 ! (从不键入),这是被迫的 CreationJson

    推荐文章