0

I use rmp_serde to serialize and deserialize some structures. One structure contains a generic type, and the compiler says:

error: the trait bound `T: api::_IMPL_SERIALIZE_FOR_User::_serde::Serialize` is not satisfied
label: the trait `api::_IMPL_SERIALIZE_FOR_User::_serde::Serialize` is not implemented for `T`

For NodeJs, messagepack works without any problems, but I'm working with rust for few days...

extern crate rmp_serde as rmps;
use bytes::Bytes;
use serde::{Deserialize, Serialize};

#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct User {
    pub name: String,
    pub token: String,
    pub hash: String,
}

#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct Message<T> {
    pub utc: u64,
    pub mtd: u64,
    pub user: User,
    pub payload: T,
}

pub fn serializeResponseMessage<T>(obj: &Message<T>) -> Vec<u8> {
    let serialized = rmps::encode::to_vec_named(&obj).unwrap();
    serialized
}

pub fn deserializeUserLoginRequest<T>(msg: &Bytes) -> Message<T> {
    // let mut obj = Message {
    //     utc: 0,
    //     mtd: 0,
    //     user: User {
    //         name: "".to_string(),
    //         token: "".to_string(),
    //         hash: "".to_string(),
    //     },
    //     payload: User {
    //         name: "".to_string(),
    //         token: "".to_string(),
    //         hash: "".to_string(),
    //     },
    // };

    let obj: Message<T> = rmps::decode::from_read_ref(&msg).unwrap();

    obj
}

How can I implement this?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Piotr Płaczek
  • 530
  • 1
  • 8
  • 20

1 Answers1

3

You need to convince rustc that T is indeed serializable and deserializable:

pub fn serializeResponseMessage<T>(obj: &Message<T>) -> Vec<u8>
where
    T: Serialize,
{
    rmps::encode::to_vec_named(obj).unwrap()
}

pub fn deserializeUserLoginRequest<'de, T>(msg: &'de Bytes) -> Message<T>
where
    T: Deserialize<'de>,
{
    rmps::decode::from_read_ref(msg).unwrap()
}
edwardw
  • 12,652
  • 3
  • 40
  • 51