我定义了两个函数来装箱 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
,我应该怎么做才能解决这个问题?可以这样使用这两个函数吗?
当您返回给定特征的类型时
impl Trait
,实际的基础类型被认为是不透明的,也就是说,它存在,编译器知道它是什么,但必须将其视为与当前范围内的任何其他类型不同。这与引入泛型类型时类似:即使(在单态化时)编译器知道实际类型,但它的行为就像除了特征约束之外没有任何信息一样。原因是每个函数的签名必须“自行”进行类型检查(同时考虑其他函数的签名)。如果您将 的实际返回类型更改
box_actix_rest_response
为实现 的其他类型Response
,它不会更改其签名,但create_file
无法进行类型检查。来自不同来源的两种不透明类型无法统一,因此会出现错误。您在这里想要的是编写实际的基础类型,而不是强制类型变得不透明:在您的情况下,它是
HttpResponse
: