Add variable custom fields to struct

In C, it is common to reserve the last field in a structure as a pointer, which can be used to add custom data to the structure:

// C code
struct Animal {
    int age;
    void *custom_data;
}

The custom_data can be used to point to some custom data that is private to a specific variable.

I am wondering if in Rust we have some similar features to do such thing?

You probably should use Option<Box<dyn YourTrait> or Option<Box<dyn Any>>. But most of time you should just use an enum and ditch the pointer if you create all instances of the struct.

1 Like

Something you control that you might extend in a specific way later?

#[non_exhaustive]
pub struct Animal {
    /* pub */ age: i32,
}

Something that needs to be extended arbitrarily (by you or downstream) now?

pub struct Animal<T /* : ?Sized */> {
    /* pub */ age: i32,
    /* pub */ supplement: T,
}
1 Like