简体   繁体   中英

How to serialize or deserialize a generic struct with messagepack?

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM