如何使用消息包序列化或反序列化通用结构?

How to serialize or deserialize a generic struct with messagepack?

我使用rmp_serde序列化和反序列化一些结构。一个结构包含泛型类型,编译器说:

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`

对于 NodeJs,messagepack 工作没有任何问题,但我用了几天生锈...

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
}

我该如何实现?

你需要让rustc相信T确实是可序列化和反序列化的:

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