是否可以有条件地启用像“derive"这样的属性? [英] Is it possible to conditionally enable an attribute like `derive`?
问题描述
我在我的 crate 中添加了一个功能,它增加了 serde
支持.但是,我不太明白如何正确使用它:
//#[derive(Debug, Serialize, Deserialize, Clone)]//转到:#[派生(调试,克隆)]#[cfg(feature = "serde_support")]#[派生(序列化,反序列化)]酒吧结构MyStruct;
此代码将 cfg(feature)
下的所有内容视为有条件编译,因此如果没有我的 serde_support
功能,我的 crate 也没有 MyStruct
.
我试图用大括号把它包裹起来,但它给出了另一个错误:
代码:
#[derive(Debug, Clone)]#[cfg(feature = "serde_support")] {#[派生(序列化,反序列化)]}酒吧结构MyStruct;
错误:
错误:属性后的预期项目-->mycrate/src/lib.rs:65:33|65 |#[cfg(feature = "serde_support")] {|^
那么如何做到这一点?
您可以使用 cfg_attr(a, b)
属性:
#[derive(Debug, Clone)]#[cfg_attr(feature = "serde_support", 派生(序列化,反序列化))]酒吧结构MyStruct;
<块引用>#[cfg_attr(a, b)]物品
与#[b] item
相同,如果a
由cfg
设置,item
否则.
I have added a feature in my crate which adds serde
support. However, I don't quite understand how to use it properly:
// #[derive(Debug, Serialize, Deserialize, Clone)] // goes to:
#[derive(Debug, Clone)]
#[cfg(feature = "serde_support")]
#[derive(Serialize, Deserialize)]
pub struct MyStruct;
This code treats everything below cfg(feature)
as conditionally compiled, so without my serde_support
feature my crate does not have MyStruct
also.
I have tried to wrap it with braces but it gives another error:
Code:
#[derive(Debug, Clone)]
#[cfg(feature = "serde_support")] {
#[derive(Serialize, Deserialize)]
}
pub struct MyStruct;
Error:
error: expected item after attributes
--> mycrate/src/lib.rs:65:33
|
65 | #[cfg(feature = "serde_support")] {
| ^
So how to do this?
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.
这篇关于是否可以有条件地启用像“derive"这样的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!