我在我的 crate 中添加了一个功能,它添加了 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
功能,我的 crate 也不会有 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")] {
| ^
那么如何做到这一点呢?
最佳答案
您可以使用 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
ifa
is set bycfg
, anditem
otherwise.
关于rust - 是否可以有条件地启用 `derive` 之类的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42551113/