1

I'm trying to write a generic function to send some data, wrapped into a parent-struct. The data should then be encoded as JSON and sent with a socket.

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

But I'm getting the following compiler error:

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<()> {
                                ^~~~~~~~~~~

No matter what I do, I was not able to find the correct generic parameters for <T>

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
olee
  • 735
  • 5
  • 14
  • What was the result when you tried with `Encoder` instead of `Encoder<'a>` ? – Shepmaster Dec 17 '14 at 18:30
  • wrong number of type arguments: expected 1, found 0 ----- fn send_request>(mut socket: TcpStream, id: &str, data: & T) -> std::io::IoResult<()> – olee Dec 17 '14 at 18:48

1 Answers1

1

What tripped me up a lot trying to get this to compile was the distinction between json::Encoder and serialize::Encoder. That error message got lost in the output, plus the existing import for Encoder made it seem like the right thing was being used.

I also changed some imports to get it to compile.

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())
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366