[英]Rust - trait bound depending on feature?
我最近開始使用 rust 並且正在開發一個庫。 以下工作,但似乎是代碼重復
#[cfg(feature = "serde_support")]
use serde::Serialize;
#[cfg(not(feature = "serde_support"))]
pub struct Teststruct<T>
{
graph: T
}
#[cfg(feature = "serde_support")]
#[derive(Serialize)]
pub struct Teststruct<T>
where T: Serialize
{
graph: T
}
請注意,雖然在此示例中不嚴格要求where T: Serialize
in 的特征綁定,但在我目前面臨的問題中它是必需的。
所以上面對我來說看起來像是不必要的代碼重復,特別是如果結構包含更多字段。 我寧願寫這樣的東西:
#[cfg(feature = "serde_support")]
use serde::Serialize;
#[cfg_attr(feature = "serde_support", derive(Serialize))]
pub struct Teststruct<T: Node>
where T: Serialize,
Graph<T>: Serialize + DeserializeOwned
{
graph: Graph<T>
}
但是,現在我只能使用“serde_support”功能進行編譯 - 如果沒有該功能,我顯然會收到錯誤:在此 scope 中找不到Serialize
。
我試圖為特征綁定找到類似 cfg_attr 的東西,但無濟於事。
有沒有一種優雅的方法來避免代碼重復?
您可以引入一個新的中間特征MySerialize
,以便您始終需要MySerialize
而不是Serialize
,因此只在一個地方進行此切換。
派生可以通過cfg_attr
解決。
#[cfg(feature = "serde_support")]
use serde::Serialize;
#[cfg(feature = "serde_support")]
pub trait MySerialize : Serialize {}
#[cfg(not(feature = "serde_support"))]
pub trait MySerialize {}
#[cfg_attr(feature = "serde_support", derive(Serialize))]
pub struct Teststruct<T>
where T: MySerialize
{
graph: T
}
或者只是使用條件編譯:
#[cfg_attr(feature = "serde_support", derive(Serialize))]
pub struct TestStruct<
#[cfg(feature = "serde_support")] T: serde::Serialize,
#[cfg(not(feature = "serde_support"))] T,
> {
graph: T
}
出於某種原因,您還不能在看起來更好的where
塊中執行此操作。 (rustc 1.55.0-nightly)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.