编码泛型类型时生命周期参数的数量错误

时间:2014-12-17 18:19:59

标签: json generics serialization rust lifetime

我正在尝试编写一个泛型函数来发送一些包含在父结构中的数据。 然后应将数据编码为JSON并使用套接字发送。

extern crate serialize;
use serialize::json;
use serialize::serialize::{Encodable, Encoder};
use std::io::{TcpStream, IoResult};

#[deriving(Decodable, Encodable)]
struct RemoteRequest<T>  {
    id: String,
  auth: RequestAuth,
  data: T,
}

fn send_request<'a, T:Encodable<Encoder<'a>>>(mut socket: TcpStream, id: &str, data: &'a T) -> IoResult<()> {
    let encoded = json::encode(&RemoteRequest {
        id: id.to_string(),
        auth: RequestAuth {
            id: "ForgeDevName".to_string(),
            pass: "password".to_string(),
        },
        data: data,
    });
    return socket.write((encoded + "\n\n\n").as_bytes())
}

但我收到以下编译错误:

error: wrong number of lifetime parameters: expected 0, found 1 [E0107]
fn send_request<'a, T:Encodable<Encoder<'a>>>(mut socket: TcpStream, id: &str, data: &'a T) -> IoResult<()> {
                                ^~~~~~~~~~~

无论我做什么,我都无法找到<T>

的正确通用参数

1 个答案:

答案 0 :(得分:1)

试图让我编译的很多东西让我感到惊讶的是json::Encoderserialize::Encoder之间的区别。该错误消息在输出中丢失,加上Encoder的现有导入使得它似乎正在被使用。

我还更改了一些导入以使其编译。

extern crate serialize;
use serialize::json;
use serialize::{Encodable, Encoder};
use std::io::{TcpStream, IoResult};
use std::io::IoError;

#[deriving(Decodable, Encodable)]
struct RequestAuth {
  id: String,
  pass: String,
}

#[deriving(Decodable, Encodable)]
struct RemoteRequest<T>  {
    id: String,
  auth: RequestAuth,
  data: T,
}

fn send_request<'a, T>(mut socket: TcpStream, id: &str, data: &T) -> IoResult<()>
   where T: Encodable<serialize::json::Encoder<'a>, IoError>
{
    let a = RemoteRequest {
        id: id.to_string(),
        auth: RequestAuth {
            id: "ForgeDevName".to_string(),
            pass: "password".to_string(),
        },
        data: data,
    };

    let encoded = json::encode(&a);

    socket.write((encoded + "\n\n\n").as_bytes())
}