首页 > 解决方案 > 是否可以使用功能标志进行条件特征继承(例如发送 + 同步)?

问题描述

在库中,人们可能希望根据特性标志将特征的实现限制为线程安全的。这有时涉及更改特征继承。但是,特征继承边界上不允许使用属性。一个常见的解决方法是复制特征:

#[cfg(not(feature = "thread_safe"))]
pub trait MyTrait {
    fn foo();
}

#[cfg(feature = "thread_safe")]
pub trait MyTrait: Send + Sync {
    fn foo();
}

可以通过使用宏(见下文)来减轻重复代码的影响,但这会使 IDE 体验受到影响。有没有更好的方法来实现条件特征继承?

macro_rules! my_trait {
    ($($bounds:ident),*) => {
        pub trait MyTrait where $(Self: $bounds),* {
            fn foo();
        }
    };
}

#[cfg(not(feature = "thread_safe"))]
my_trait!();
#[cfg(feature = "thread_safe")]
my_trait!(Send, Sync);

标签: rust

解决方案


推荐阅读