You can use the cfg_attr(a, b)
attribute:
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub struct MyStruct;
It’s described in the Rust reference about “conditional compilation”:
#[cfg_attr(a, b)] item
Will be the same as
#[b] item
ifa
is set bycfg
, anditem
otherwise.
More Related Contents:
- Why do I need to import a trait to use the methods it defines for a type?
- Why does linking lifetimes matter only with mutable references?
- Why is adding a lifetime to a trait with the plus operator (Iterator + ‘a) needed?
- Should trait bounds be duplicated in struct and impl?
- Can I do type introspection with trait objects and then downcast it?
- How can I perform parallel asynchronous HTTP GET requests with reqwest?
- Convert a String to int?
- How do I borrow a RefCell, find a key, and return a reference to the result? [duplicate]
- Is there a way other than traits to add methods to a type I don’t own?
- What’s the Rust idiom to define a field pointing to a C opaque pointer?
- Trait implementation for both a trait object and for direct implementors of the trait
- Can’t borrow mutably within two different closures in the same scope
- How can I implement Rust’s Copy trait?
- How to iterate over and filter an array?
- How to use a struct’s member as its own key when inserting the struct into a map without duplicating it?
- If BufReader takes ownership of a stream, how can I read and write lines on it?
- How to fix lifetime error when function returns a serde Deserialize type?
- Is there another option to share an Arc in multiple closures besides cloning it before each closure?
- Understanding Traits and Object Safety
- How to implement a custom ‘fmt::Debug’ trait?
- How do I pass a closure through raw pointers as an argument to a C function?
- Is there a way to use existing structs as enum variants?
- How can I create enums with constant values in Rust?
- How do I use a crate from another crate without explicitly defining a new dependency in my project?
- Can’t implement a trait I don’t own for all types that implement a trait I do own
- Creating a vector of zeros for a specific size
- What is the difference between immutable and const variables in Rust?
- What is the purpose of the unit type in Rust?
- How to print structs and arrays?
- Can Rust optimise away the bit-wise copy during move of an object someday?