rust - 是否可以使用功能标志进行条件特征继承(例如发送 + 同步)?
问题描述
在库中,人们可能希望根据特性标志将特征的实现限制为线程安全的。这有时涉及更改特征继承。但是,特征继承边界上不允许使用属性。一个常见的解决方法是复制特征:
#[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);
解决方案
推荐阅读
- visual-studio-code - 自动缩进不适用于 SAS 语言扩展
- javascript - 从 props 数组中按索引值删除
- javascript - MutationObserver 在按下空格时调用了两次
- python - 在 kivy 标签中使用孟加拉语文本(孟加拉语)
- c# - 如何在React组件类中绑定和调用c# obejct的方法
- reactjs - 父子组件之间的回调函数
- python - 如何对每个 n 数组值求和并将结果放入一个新数组中?
- microsoft-teams - 如何区分 Microsoft Teams 中的两个用户?
- python - 字典访问正在停止代码流
- node.js - 从 res.sendFile() 获取 req 对象