AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题 / 76987201
Accepted
Dolphin
Dolphin
Asked: 2023-08-27 20:52:43 +0800 CST2023-08-27 20:52:43 +0800 CST 2023-08-27 20:52:43 +0800 CST

`impl Trait` 的不同使用导致 Rust 中不同的不透明类型

  • 772

我定义了两个函数来装箱 actix_web 响应,如下所示:

pub fn box_actix_rest_response<T>(data: T) -> impl Responder where T: Serialize + Default{
    let res = ApiResponse {
        result: data,
        ..Default::default()
    };
    HttpResponse::Ok().json(res)
}

pub fn box_error_actix_rest_response <T>(data: T, result_code: String, msg: String) -> impl Responder where T: Serialize + Default {
    let res = ApiResponse {
        result: data,
        statusCode: "200".to_string(),
        resultCode: result_code,
        msg
    };
    HttpResponse::Ok().json(res)
}

一个函数包装正常响应,另一个包装错误响应,但是当我在同一外层函数中使用这两个函数时,如下所示:

pub fn create_file(add_req: &TexFileAddReq, login_user_info: &LoginUserInfo) -> impl Responder {
    let new_file = TexFileAdd::gen_tex_file(add_req, login_user_info);
    use crate::model::diesel::tex::tex_schema::tex_file as cv_work_table;
    use crate::model::diesel::tex::tex_schema::tex_file::dsl::*;
    let mut query = cv_work_table::table.into_boxed::<diesel::pg::Pg>();
    query = query.filter(
        cv_work_table::parent
            .eq(add_req.parent.clone())
            .and(cv_work_table::name.eq(add_req.name.clone()))
            .and(cv_work_table::file_type.eq(add_req.file_type.clone())),
    );
    let cvs = query.load::<TexFile>(&mut get_connection()).unwrap();
    if !cvs.is_empty() {
        return box_error_actix_rest_response("already exists", "ALREADY_EXISTS".to_owned(), "file/folder already exists".to_owned());
    }
    let result = diesel::insert_into(tex_file)
        .values(&new_file)
        .get_result::<TexFile>(&mut get_connection())
        .expect("failed to add new tex file or folder");
    let resp = box_actix_rest_response(result);
    return resp;
}

显示错误:

mismatched types
expected opaque type `impl Responder` (opaque type at </Users/xiaoqiangjiang/.cargo/git/checkouts/rust_wheel-8476ff1b418e67f8/252bdd6/src/common/wrapper/actix_http_resp.rs:23:88>)
   found opaque type `impl Responder` (opaque type at </Users/xiaoqiangjiang/.cargo/git/checkouts/rust_wheel-8476ff1b418e67f8/252bdd6/src/common/wrapper/actix_http_resp.rs:15:47>)
distinct uses of `impl Trait` result in different opaque typesrustcClick for full compiler diagnostic
actix_http_resp.rs(23, 88): the expected opaque type
actix_http_resp.rs(15, 47): the found opaque type
file_service.rs(106, 81): expected `impl Responder` because of return type

看起来两个函数返回不同Responder,我应该怎么做才能解决这个问题?可以这样使用这两个函数吗?

rust
  • 1 1 个回答
  • 30 Views

1 个回答

  • Voted
  1. Best Answer
    jthulhu
    2023-08-27T21:26:07+08:002023-08-27T21:26:07+08:00

    当您返回给定特征的类型时impl Trait,实际的基础类型被认为是不透明的,也就是说,它存在,编译器知道它是什么,但必须将其视为与当前范围内的任何其他类型不同。这与引入泛型类型时类似:即使(在单态化时)编译器知道实际类型,但它的行为就像除了特征约束之外没有任何信息一样。

    原因是每个函数的签名必须“自行”进行类型检查(同时考虑其他函数的签名)。如果您将 的实际返回类型更改box_actix_rest_response为实现 的其他类型Response,它不会更改其签名,但create_file无法进行类型检查。

    来自不同来源的两种不透明类型无法统一,因此会出现错误。您在这里想要的是编写实际的基础类型,而不是强制类型变得不透明:在您的情况下,它是HttpResponse:

    pub fn box_actix_rest_response<T>(data: T) -> HttpResponse where T: Serialize + Default{
        let res = ApiResponse {
            result: data,
            ..Default::default()
        };
        HttpResponse::Ok().json(res)
    }
    
    pub fn box_error_actix_rest_response <T>(data: T, result_code: String, msg: String) -> HttpResponse where T: Serialize + Default {
        let res = ApiResponse {
            result: data,
            statusCode: "200".to_string(),
            resultCode: result_code,
            msg
        };
        HttpResponse::Ok().json(res)
    }
    
    • 1

相关问题

  • 在匹配内重用函数时,匹配臂具有预期的不兼容类型

  • match 语句中的 Rust 类型转换

  • 如何强制匹配的返回类型为()?

  • 原始表示中的 Rust 枚举

  • 有没有办法直接简化 Result<String, VarError> 中 Ok("VAL") 的匹配

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    使用 <font color="#xxx"> 突出显示 html 中的代码

    • 2 个回答
  • Marko Smith

    为什么在传递 {} 时重载解析更喜欢 std::nullptr_t 而不是类?

    • 1 个回答
  • Marko Smith

    您可以使用花括号初始化列表作为(默认)模板参数吗?

    • 2 个回答
  • Marko Smith

    为什么列表推导式在内部创建一个函数?

    • 1 个回答
  • Marko Smith

    我正在尝试仅使用海龟随机和数学模块来制作吃豆人游戏

    • 1 个回答
  • Marko Smith

    java.lang.NoSuchMethodError: 'void org.openqa.selenium.remote.http.ClientConfig.<init>(java.net.URI, java.time.Duration, java.time.Duratio

    • 3 个回答
  • Marko Smith

    为什么 'char -> int' 是提升,而 'char -> Short' 是转换(但不是提升)?

    • 4 个回答
  • Marko Smith

    为什么库中不调用全局变量的构造函数?

    • 1 个回答
  • Marko Smith

    std::common_reference_with 在元组上的行为不一致。哪个是对的?

    • 1 个回答
  • Marko Smith

    C++17 中 std::byte 只能按位运算?

    • 1 个回答
  • Martin Hope
    fbrereto 为什么在传递 {} 时重载解析更喜欢 std::nullptr_t 而不是类? 2023-12-21 00:31:04 +0800 CST
  • Martin Hope
    比尔盖子 您可以使用花括号初始化列表作为(默认)模板参数吗? 2023-12-17 10:02:06 +0800 CST
  • Martin Hope
    Amir reza Riahi 为什么列表推导式在内部创建一个函数? 2023-11-16 20:53:19 +0800 CST
  • Martin Hope
    Michael A fmt 格式 %H:%M:%S 不带小数 2023-11-11 01:13:05 +0800 CST
  • Martin Hope
    God I Hate Python C++20 的 std::views::filter 未正确过滤视图 2023-08-27 18:40:35 +0800 CST
  • Martin Hope
    LiDa Cute 为什么 'char -> int' 是提升,而 'char -> Short' 是转换(但不是提升)? 2023-08-24 20:46:59 +0800 CST
  • Martin Hope
    jabaa 为什么库中不调用全局变量的构造函数? 2023-08-18 07:15:20 +0800 CST
  • Martin Hope
    Panagiotis Syskakis std::common_reference_with 在元组上的行为不一致。哪个是对的? 2023-08-17 21:24:06 +0800 CST
  • Martin Hope
    Alex Guteniev 为什么编译器在这里错过矢量化? 2023-08-17 18:58:07 +0800 CST
  • Martin Hope
    wimalopaan C++17 中 std::byte 只能按位运算? 2023-08-17 17:13:58 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve