Skip to content
This repository was archived by the owner on Aug 15, 2025. It is now read-only.
This repository was archived by the owner on Aug 15, 2025. It is now read-only.

derive Decode and trait containing a type #769

@nduchaux

Description

@nduchaux

Hello,

Trying to derive

use bincode::{Decode, Encode};

pub trait Trait {
    type Type: Clone + Encode + Decode<()>;
}

#[derive(Clone, Encode, Decode)]
pub struct A<T>
where
    T: Trait,
{
    id: T::Type,
}

gives:

#[derive(Clone, Encode, Decode)]
                        ^^^^^^ the trait `Decode<__Context>` is not implemented for `<T as Trait>::Type`
#[derive(Clone, Encode, Decode)]
                        ^^^^^^ the trait `BorrowDecode<'_, __Context>` is not implemented for `<T as Trait>::Type`

Manually implementing the Decode and BorrowDecode is ok.

impl<Context, T> bincode::Decode<Context> for A<T>
where
    T: Trait,
    <T as Trait>::Type: bincode::Decode<Context>,
{
    fn decode<D: bincode::de::Decoder<Context = Context>>(
        decoder: &mut D,
    ) -> core::result::Result<Self, bincode::error::DecodeError> {
        Ok(Self {
            id: bincode::Decode::decode(decoder)?,
        })
    }
}
impl<'de, Context, T> bincode::BorrowDecode<'de, Context> for A<T>
where
    T: Trait,
    <T as Trait>::Type: bincode::BorrowDecode<'de, Context>,
{
    fn borrow_decode<D: bincode::de::BorrowDecoder<'de, Context = Context>>(
        decoder: &mut D,
    ) -> core::result::Result<Self, bincode::error::DecodeError> {
        Ok(Self {
            id: bincode::BorrowDecode::borrow_decode(decoder)?,
        })
    }
}

You probably forgot to add the bounds of the trait type in the derive macro.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions