2017-03-02 70 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")] { 
    |        ^

那么,如何做到这一点?

回答

9

可以使用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 

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

+1

这是非常有用的 - 它的怪异,它不是更好的文档暴露。 – ljedrz

相关问题