Skip to content

Conditional derive #188

@lecanard539

Description

@lecanard539

When implementing REST API clients, I usually derive Serialize and Default conditionally for tests, like so:

#[derive(Debug, Deserialize)]
#[cfg_attr(test, derive(Serialize, Default))]
pub struct SlavaUkraini {
    pub field: String,
    pub something: u64,
}

This enables me to use Default and Serialize in tests to easily and quickly instantiate mock responses, while at the same time keeping the prod binary smaller and prod compile times lower.
Unfortunately conditional derive doesn't currently seem possible in nutype.

Would it be possible to enable nutype to do something similar? Like

#[nutype(derive(Debug, Deserialize, AsRef), cfg_attr(test, derive(Default, Serialize))]
pub struct HeroyamSlava(String);

#[derive(Debug, Deserialize)]
#[cfg_attr(test, derive(Serialize, Default))]
pub struct SlavaUkraini {
    pub field: HeroyamSlava,
    pub something: u64,
}

Or maybe

#[nutype(derive(Debug, Deserialize, AsRef)]
#[cfg_attr(test, nutype(derive(Default, Serialize))]
pub struct HeroyamSlava(String);

Whatever makes the most sense. I am a complete noob when it comes to Rust macros, and proc macros especially, so no idea what the best solution would be.

This request is not super important, as it works just fine without the conditional derive, it would just be nice to have.

Actually now that I think about it, it would also be nice to have this for libraries wanting to conditionally derive on feature flags, not just on tests.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions