2017-03-02 2 views
8

serdeをサポートする機能を追加しました。しかし、私はかなりそれを正しく使用する方法を理解していない: 条件付きでフィーチャで派生することはできますか?

// #[derive(Debug, Serialize, Deserialize, Clone)] // goes to: 

#[derive(Debug, Clone)] 
#[cfg(feature = "serde_support")] 
#[derive(Serialize, Deserialize)] 
pub struct MyStruct; 

は現在、このコードはので、私のクレートも MyStructを持っていない私の serde_support機能せず、 cfg(feature)が条件付きコンパイルの下にすべてを扱います。

私は中括弧でそれをラップしようとしたが、それは別のエラーを与える:

コード:

#[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")] { 
    |        ^

これを行うには、どのように?

#[derive(Debug, Clone)] 
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))] 
pub struct MyStruct; 

それはRust reference about "conditional compilation"で説明しています:

答えて

9

あなたがcfg_attr(a, b)属性を使用することができ非常に便利です

#[cfg_attr(a, b)] 
item 

Will be the same as #[b] item if a is set by cfg , and item otherwise.

+1

を - それは、より良いドキュメントにさらされていないということ奇妙です。 – ljedrz

関連する問題