是否可以有条件地启用像“derive"这样的属性? [英] Is it possible to conditionally enable an attribute like `derive`?

查看:69
本文介绍了是否可以有条件地启用像“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;

它在 关于条件编译"的 Rust 参考资料中有描述:

<块引用>

#[cfg_attr(a, b)]物品

#[b] item相同,如果acfg设置,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 if a is set by cfg, and item otherwise.

这篇关于是否可以有条件地启用像“derive"这样的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆