【问题标题】:Conditionally derive based on feature flag [duplicate]基于特征标志有条件地派生[重复]
【发布时间】:2017-02-05 07:16:33
【问题描述】:

我想在我的 crate 中添加一个功能,可以选择性地使某些结构可序列化,特别是,我想使用 Serde 的自定义派生宏。 Serde 依赖项是可选的,extern crate 声明有条件地包含在该功能后面。考虑以下几点:

#[derive(Eq, PartialEq, Serialize)]
struct MyStruct {
    a: u8,
    b: u8
}

启用功能标志后,一切正常。禁用它后,我会收到以下警告:

error: '#[derive]' for custom traits is not stable enough for use. It is deprecated and will be removed in v1.15 (see issue #29644)

有没有办法有条件地包含派生特征?我正在使用 Rust 1.15 稳定版。

我应该为错误消息提交问题吗?这似乎具有误导性。

【问题讨论】:

    标签: rust


    【解决方案1】:

    像许多其他基于特征的条件编译一样,使用cfg_attr

    #[cfg_attr(feature = "example", derive(Debug))]
    struct Foo;
    
    fn main() {
        println!("{:?}", Foo);
    }
    

    这样,cargo run 将无法编译,因为 Debug 未针对 Foo 实现,但 cargo run --features example 将编译并运行成功。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-25
      • 2017-11-21
      • 2019-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多