错误:类型参数"D"必须用作某些本地类型的类型参数 [英] error: type parameter `D` must be used as the type parameter for some local type

查看:148
本文介绍了错误:类型参数"D"必须用作某些本地类型的类型参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Nickel.rs与MongoDB结合使用以构建RESTful api. 我想为类型mongodb::error::Result<Option<bson::Document>>实现一个通用的Responder.

I'm using Nickel.rs with MongoDB to build a RESTful api. I'd like to implement a generic Responder for the type mongodb::error::Result<Option<bson::Document>>.

这是我根据为Responder找到的示例编写的实现:

This is the implementation I wrote based on the examples I found for Responder:

impl<D> Responder<D> for Result<Option<Document>> {

    fn respond<'a>(self, mut response: Response<'a, D>) -> MiddlewareResult<'a, D> {
        response.set(MediaType::Json);

        match self {
            Ok(Some(doc))=>{
                ApiResponse{data: Bson::Document(doc).to_json()}.to_json()
            },
            Ok(None)=>{
                response.set(StatusCode::NotFound);
                ApiError{error: "Not found".to_string()}.to_json()
            },
            Err(e)=>{
                response.set(StatusCode::InternalServerError);
                ApiError{error: format!("{}",e)}.to_json()
            }

        }
    }
}

我收到以下错误:

错误:类型参数D必须用作某些类型的类型参数 本地类型(例如MyStruct<T>);仅当前定义的特征 可以为类型参数[E0210]实现板条箱

error: type parameter D must be used as the type parameter for some local type (e.g. MyStruct<T>); only traits defined in the current crate can be implemented for a type parameter [E0210]

我运行rustc --explain E0210进行了解释,如果我的理解是正确的,我需要提供一个特征D作为impl<D>的类型参数,但是我不知道要提供哪个特征.

I ran rustc --explain E0210 for an explanation and if my understanding is correct, I need to provide a trait D as a type argument to impl<D>, but I don't understand which trait to provide.

我尝试了impl<D: =()>,但是产生了相同的错误.

I tried impl<D: =()> but that produced the same error.

推荐答案

实现特质后,

When you implement a trait then either the trait or the type you are implementing it for must be defined in the same crate. In you example that is not the case: the trait Responder is defined by nickel, and Result is defined by mongodb.

解决此问题的常用方法是通过将所需的类型包装到元组结构具有单个组件(所谓的 newtype模式):

The common way to work around this is to define your own type, by wrapping the desired type into a tuple struct with a single component (the so-called newtype pattern):

struct Result(mongodb::error::Result<Option<Document>>);

impl Responder for Result {
    ...

这篇关于错误:类型参数"D"必须用作某些本地类型的类型参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆