rust - 是否可以有条件地启用 `derive` 之类的属性?

标签 rust

我在我的 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 if a is set by cfg, and item otherwise.

关于rust - 是否可以有条件地启用 `derive` 之类的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42551113/

相关文章:

rust - 在 Rust 中读取字符串并将其解析为迭代器的函数

arrays - 来自范围的常量数组

rust - 如何设置返回值的生命周期?

rust - 如何正确解决结构中的生命周期推断?

rust - 即使 NLL 打开,循环中的双可变借用错误也会发生

rust - HashMap 键的生命周期不够长

enums - 匹配包含附件数据的枚举的所有变体

rust - Rust 中的严格别名?

arrays - 如何在 Rust 中将一串数字转换为数组或整数向量?