Conditional Directives

Hello all,

I have a struct with a chrono::Utc member that I de/serialize with serde. I'd like to optionally support serializing to mongo, and I'd like the timestamp member to be serialized as a mongodb "ISODate".

mongo is an optional feature of the crate, and I'm not sure how to make the extra serialization directive dependent on the feature. Here's my attempt:

pub use chrono::{DateTime, Utc};
pub use serde::{Deserialize, Serialize};

#[derive(Clone, Debug, Serialize, Deserialize)]
struct Record {
    #[serde(default = "chrono::Utc::now)]"
    #[cfg(feature = "mongo")]
    #[serde(with = "bson::serde_helpers::chrono_datetime_as_bson_datetime")]
    pub start_time: DateTime<Utc>,

    pub message: String,
}

If the crate is compiled w/o --features mongo, then start_time doesn't appear in the code.

Is there a way to conditionally specify directives based on feature flags?

I belive you have to use cfg_attr in this case.

You are awesome, thank you very much. For future reference, here's the updated code:

pub use chrono::{DateTime, Utc};
pub use serde::{Deserialize, Serialize};

#[derive(Clone, Debug, Serialize, Deserialize)]
struct Record {
    #[serde(default = "chrono::Utc::now")]
    #[cfg_attr(
        feature = "mongo",
        serde(with = "bson::serde_helpers::chrono_datetime_as_bson_datetime")
    )]
   pub start_time: DateTime<Utc>,

   pub message: String,
}

Also, I've learned that these are attributes, not directives :slight_smile: . Thanks very much!

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.