gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:25:58 25 4
gpt4 key购买 nike

我使用 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 工作没有任何问题,但我已经用 rust 工作了几天......

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

关于generics - 如何使用消息包序列化或反序列化通用结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58522793/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com