You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Serde无法为泛型结构体自动派生序列化/反序列化问题

泛型结构体HashStore的Serde+Postcard序列化/反序列化实现需求

我需要使用serde和postcard对泛型结构体HashStore<T: ImgHashOutput>进行序列化与反序列化。理想情况下希望支持所有ImgHashOutput类型,但目前只需保证u128类型可用即可。

涉及的结构体与Trait

pub trait ImgHashOutput:
    Default + AddAssign + ShlAssign<u8> + From<u8> + Copy + IntegerStuff + Serialize + DeserializeOwned {}

impl<T> ImgHashOutput for T where
    T: Default + AddAssign + ShlAssign<u8> + From<u8> + Copy + IntegerStuff + Serialize + DeserializeOwned {}

// 存储与特定字符对应的感知图像哈希集合
#[derive(Debug, Serialize, Deserialize)]
pub struct StoreValue<T: ImgHashOutput> {
    pub value: char,
    pub hashes: Vec<T>,
}

// 存储所有可识别字符对应的StoreValue集合
#[derive(Debug, Serialize, Deserialize)]
pub struct HashStore<T: ImgHashOutput> {
    pub arr: Vec<StoreValue<T>>
}

pub trait SerdeStoreValue:
    Serialize + DeserializeOwned
{}

impl<T> SerdeStoreValue for T where
    T: Serialize + DeserializeOwned
{}

当前可正常运行的参考代码

pub trait IntegerStuff {
    const BITS: u32;
    fn hamming_dist<T: ImgHashOutput>(a: Self, b: Self) -> u32;
}

macro_rules! impl_integer_stuff {
    ($type:ty) => {
        impl IntegerStuff for $type {
            const BITS: u32 = (<$type>::BITS) as u32;
        
            #[inline(always)]
            fn hamming_dist<T: ImgHashOutput>(a: Self, b: Self) -> u32 {
                (a ^ b).count_ones() as u32
            }
        }
    };
}

impl_integer_stuff!(i8);
impl_integer_stuff!(u8);
impl_integer_stuff!(i16);
impl_integer_stuff!(u16);
impl_integer_stuff!(i32);
impl_integer_stuff!(u32);
impl_integer_stuff!(i64);
impl_integer_stuff!(u64);
impl_integer_stuff!(i128);
impl_integer_stuff!(u128);
impl_integer_stuff!(isize);
impl_integer_stuff!(usize);

内容的提问来源于stack exchange,提问作者Mining15

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 11:43:19