Skip to content

Derive attributes

Finn Bear edited this page Jul 16, 2025 · 6 revisions

When you #[derive(Encode, Decode)], you have access to the following attributes:

#[bitcode(skip)]

Use this attribute to skip encoding a particular field, and to use a Default value when decoding.

#[derive(Encode, Decode)]
struct Image {
    bytes: Vec<u8>,
    // Will be empty when decoded.
    #[bitcode(skip)]
    thumbnail_cache: Vec<u8>,
}

impl Image {
    fn thumbnail(&mut self) -> &[u8] {
        if self.thumbnail_cache.is_empty() {
            self.thumbnail_cache = generate_thumbnail(&self.bytes);
        }
        &self.thumbnail_cache
    }
}

#[bitcode(bound_type = "...")]

By default, #[derive(Encode, Decode)] will create a T: Encode + Decode bound for any type T mentioned by an item field.

You can use this attribute to override that behavior.

#[derive(Encode, Decode)]
pub struct MyPhantomData<A>(std::marker::PhantomData<A>);

#[derive(Encode, Decode)]
struct Spooky<A> {
    // Bound will be `MyPhantomData<A>: Encode + Decode`
    // instead of `A: Encode + Decode`.
    #[bitcode(bound_type = "MyPhantomData<A>")]
    field: MyPhantomData<A>,
}

// Thanks to the attribute, it is now possible to use `Spooky`
// with a type that doesn't implement `Encode` or `Decode`.
pub struct NoEncodeDecode;
let _ = bitcode::encode(&Spooky{
    field: MyPhantomData::<NoEncodeDecode>(Default::default()),
});

#[bitcode(crate = "...")]

You can use this attribute if you import bitcode under an alias.

# Cargo.toml
bitcode_renamed = { package = "bitcode", version = "0.6" }
// main.rs
#[derive(bitcode_renamed::Encode)]
#[bitcode(crate = "bitcode_renamed")]
pub struct MyData {
    // ...
}

Clone this wiki locally