2017-03-02 11 views
8

मैंने अपने क्रेट में एक सुविधा जोड़ा है जो serde समर्थन जोड़ता है। हालांकि, मैं काफी कैसे ठीक इसका इस्तेमाल करने की समझ में नहीं आता:क्या सशर्त रूप से सुविधाओं के साथ प्राप्त करना संभव है?

// #[derive(Debug, Serialize, Deserialize, Clone)] // goes to: 

#[derive(Debug, Clone)] 
#[cfg(feature = "serde_support")] 
#[derive(Serialize, Deserialize)] 
pub struct MyStruct; 

वर्तमान में इस कोड को नीचे दिए गए cfg(feature) सशर्त संकलित सब कुछ व्यवहार करता है तो मेरे serde_support सुविधा मेरे टोकरा भी MyStruct नहीं है बिना।

मैं ब्रेसिज़ के साथ लपेट की कोशिश की है, लेकिन यह एक और त्रुटि देता है:

कोड:

#[derive(Debug, Clone)] 
#[cfg(feature = "serde_support")] { 
#[derive(Serialize, Deserialize)] 
} 
pub struct MyStruct; 

त्रुटि:

error: expected item after attributes 
    --> mycrate/src/lib.rs:65:33 
    | 
65 | #[cfg(feature = "serde_support")] { 
    |        ^

तो यह कैसे करना है?

#[derive(Debug, Clone)] 
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))] 
pub struct MyStruct; 

यह Rust reference about "conditional compilation" में वर्णित है:

उत्तर

9

आप cfg_attr(a, b) विशेषता का उपयोग कर सकते हैं

#[cfg_attr(a, b)] 
item 

Will be the same as #[b] item if a is set by cfg , and item otherwise.

+1

कि बहुत उपयोगी है - यह अजीब है कि यह बेहतर डॉक्स में उजागर नहीं कर रहा है। – ljedrz

संबंधित मुद्दे

 संबंधित मुद्दे