关联类型,用于通过特征和泛型类型规范化可序列化数据

问题描述 投票:2回答:1

我试图实现一种类型,可以在Tide中“强制”一些模式到我的响应,但继续得到“只能使用traits的项目......”编译器错误。

#![feature(async_await, futures_api, await_macro, arbitrary_self_types)]
#![allow(proc_macro_derive_resolution_fallback)]

use serde_derive::Serialize;
use tide::{body::Json, IntoResponse, Response};

#[derive(Serialize)]
struct Document<Attrs, Rels> {
    data: PrimaryData<Attrs, Rels>,
}

#[derive(Serialize)]
struct PrimaryData<Attrs, Rels> {
    id: i32,
    kind: String,
    attributes: Attrs,
    relationships: Rels,
}

trait IntoPrimaryData: Send {
    type Attrs: serde::Serialize;
    type Rels: serde::Serialize;

    fn into_primary_data(self) -> PrimaryData<Self::Attrs, Self::Rels>;
}

struct ServiceResponse<T: IntoPrimaryData>(T);

impl<T: IntoPrimaryData> IntoResponse for ServiceResponse<T> {
    fn into_response(self) -> Response {
        Json(Document {
            data: self.0.into_primary_data(),
        })
        .with_status(http::status::StatusCode::OK)
        .into_response()
    }
}

#[derive(Serialize)]
struct User {
    id: i32,
    primary_email: String,
}

#[derive(Serialize)]
struct UserAttrs {
    primary_email: String,
}

impl IntoPrimaryData for User {
    type Attrs = UserAttrs;
    type Rels = ();

    fn into_primary_data(self) -> PrimaryData<Self::Attrs, Self::Rels> {
        PrimaryData {
            id: self.id,
            kind: "user".into(),
            attributes: UserAttrs {
                primary_email: self.primary_email,
            },
            relationships: (),
        }
    }
}

fn main() {}
[dependencies]
tide = "0.0.5"
http = "0.1.16"
serde = "1.0.89"
serde_derive = "1.0.89"

编译器返回错误

error[E0599]: no method named `with_status` found for type `tide::body::Json<Document<<T as IntoPrimaryData>::Attrs, <T as IntoPrimaryData>::Rels>>` in the current scope
  --> src/main.rs:34:10
   |
34 |         .with_status(http::status::StatusCode::OK)
   |          ^^^^^^^^^^^
   |
   = note: the method `with_status` exists but the following trait bounds were not satisfied:
           `tide::body::Json<Document<<T as IntoPrimaryData>::Attrs, <T as IntoPrimaryData>::Rels>> : tide::response::IntoResponse`
   = help: items from traits can only be used if the trait is implemented and in scope
   = note: the following trait defines an item `with_status`, perhaps you need to implement it:
           candidate #1: `tide::response::IntoResponse`

我不知道为什么我会收到这个错误,但我觉得这与data: self.0.into_primary_data()线不够“具体”并且不知道Self::AttrsSelf::Rels的类型有什么关系。但是,我知道我也得到了同样的错误(减去关于“来自traits的项目只能是......”的帮助提示)如果其中一个嵌套类型没有实现serde::Serialize但是我可以告诉我,我已经在他们需要的任何地方添加了那些边界。

我已经尝试过现在感觉像百万种方式,并且似乎无法想出一种方法来为我的响应获得一些标准化结构。

我正在使用rustc 1.34.0-nightly (02c4c2892 2019-02-26)

compiler-errors scope rust traits
1个回答
2
投票

您尚未正确指定关联类型的完整边界。

Json只在它包含的类型实现IntoResponseSend时才实现Serialize

impl<T: Send + Serialize> IntoResponse for Json<T>

您需要在关联类型的边界中包含Send

trait IntoPrimaryData: Send {
    type Attrs: serde::Serialize + Send;
    //                           ^^^^^^
    type Rels: serde::Serialize + Send;
    //                          ^^^^^^

    fn into_primary_data(self) -> PrimaryData<Self::Attrs, Self::Rels>;
}

Debugging steps

错误消息的这一行似乎很有希望:

the method `with_status` exists but the following trait bounds were not satisfied:
`tide::body::Json<Document<<T as IntoPrimaryData>::Attrs, <T as IntoPrimaryData>::Rels>> : tide::response::IntoResponse`

这表明我们可以调用with_status,除了编译器不知道该类型实现了特征。从那里,我去了Json的文档,看看它是否实现了IntoRespose,如果是,在什么条件下:

impl<T: Send + Serialize> IntoResponse for Json<T>

基于此,我们知道这个T必须是PrimaryData<T::Attrs, T::Rels>,它必须实现Send + Serialize

我们看到PrimaryData派生出Serialize

#[derive(Serialize)]
struct PrimaryData<Attrs, Rels> {

根据现有知识,我知道大多数derived特征要求所有泛型类型也实现特征。这不太明显,但Send也是如此。

从那里,这是一个证明AttrsRels的具体类型实现SerializeSend的问题。关联的类型边界处理一个但不处理另一个。

决定在哪里放置边界是一个意图和风格的问题 - 他们可以继续功能,impl块,或在特征。由于这个特性已经提到了Serialize,它似乎是一个增加额外界限的自然场所。

我也做了一个大错误 - 我假设你已经正确指定了边界并且遇到了a compiler limitationalso)。只有当我尝试应用建议的副本时,我才意识到边界是不正确的。

也可以看看:

© www.soinside.com 2019 - 2024. All rights reserved.