Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

mongodb - error: type parameter `D` must be used as the type parameter for some local type

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>>.

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

        }
    }
}

and I'm getting the following error:

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]

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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 {
    ...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...