特征`rustc_serialize :: json :: ToJson`没有为`Json`类型实现

时间:2016-02-12 19:20:03

标签: rust

我正在使用Nickel.rs和MongoDB来创建REST API。我已经定义了一个enum ApiResult<T>,我为它实现了nickel::Responder特征。可以从实现特征ApiResult<T>的任何类型生成ToApiResult。我正在尝试为mongodb::error::Result<Option<bson::Document>>实现此特性,但我收到错误:

  

特征rustc_serialize::json::ToJson未实现   输入Json

我查看了文档,可以看到已为ToJson实施了Json

impl ToJson for Json {
    fn to_json(&self) -> Json { self.clone() }
}

那么导致错误的原因是什么?这是一个MCVE,它可以重现这个问题:

    // rustc_serialize
extern crate rustc_serialize;
use rustc_serialize::json::{self,Json, ToJson};
use std::{result,error};

enum ApiResult<T : Sized + ToJson>{
    Ok(T),
    Err(T)
}

trait ToApiResult<T: Sized + ToJson>{
    fn to_api_result(&self)->ApiResult<T>;
}

impl<Json> ToApiResult<Json> for Result<Option<String>,String> {

    fn to_api_result(&self)->ApiResult<Json>{

        match *self {
            Ok(Some(text))=>{
                ApiResult::Ok(text.to_json())
            },
            Ok(None)=>{
                ApiResult::Error(().to_json())
            },
            Err(e)=>{
                ApiResult::Error(e.to_json())
            }

        }
    }

}

fn main(){
    let r = Result::Ok(Some("hello"));
    print!("{}",r.to_api_result());
}

1 个答案:

答案 0 :(得分:4)

The problem occurs here:

    ArrayList<ObjectId> vals = new ArrayList<ObjectId>();
    vals.add(objectId);       
    BasicDBObject inQuery = new BasicDBObject("$in", vals);
    BasicDBObject query = new BasicDBObject("connectedWithIds", inQuery);
    List<BasicDBObject> users = (List<BasicDBObject>) customQueryManager.executeQuery("node", query);

Specifically, this defines a new generic type parameter called impl<Json> ToApiResult<Json> for Result<Option<String>, String> // ^^^^ . This is not the Json enum.

Beyond that, you have some other small errors that prevent compilation. Once the main error is cleared up, you would have to address:

  1. Typos (rustc_serialize::json::Json vs Error)
  2. Using a Err as opposed to a &str.
  3. Printing a non-String type with Display.
  4. Trying to move out of borrowed values.

All the issues fixed, the code looks like:

{}