是否有可能有条件地启用像“derive”这样的属性?

时间:2017-03-02 09:12:11

标签: rust

我在我的包中添加了一项功能,增加了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")] {
   |                                 ^

那怎么办呢?

1 个答案:

答案 0 :(得分:22)

您可以使用cfg_attr(a, b)属性:

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

Rust reference about "conditional compilation"中描述了

#[cfg_attr(a, b)]
item
     如果#[b] itema设置,则cfgitem相同,否则为import Foundation // Dictionary containing data as provided in your question. var dictonary : [String : Any] = ["question":"If you want to create a custom class which can be displayed on the view, you can subclass UIView.", "answers":["True", "False"], "correctIndex":0, "module":3, "lesson":0, "feedback":"Subclassing UIView gives your class the methods and properties of a basic view which can be placed onto the view." ] if let jsonData = try JSONSerialization.data(withJSONObject: dictonary, options: .init(rawValue: 0)) as? Data { // Check if everything went well print(NSString(data: jsonData, encoding: 1)!) // Do something cool with the new JSON data }