我可以定义必须执行`!Send`的特征吗? [英] Can I define a trait whose implementations must be `!Send`?
问题描述
我想定义一个特质,该特质强制其实现者在任何情况下都不能发送到线程或在线程之间共享.将特征标记为!Send
就足够了,但是Rust似乎不让我这么做.
I'd like to define a trait which forces its implementors to under no circumstances be sent to, or shared between, threads. It should suffice to mark the trait as !Send
, but Rust doesn't seem to let me.
有可能吗?
示例(游乐场):
#![feature(optin_builtin_traits)]
// This is a syntax error
//trait ThreadThing : !Send {}
// This doesn't work either
trait ThreadThing { }
impl !Send for ThreadThing {}
推荐答案
不,您不能将!Send
设置为ThreadThing
的条件.编译器只是不支持这种逻辑.
No, you can't make !Send
a condition of ThreadThing
. The compiler just doesn't support that kind of logic.
如果某人可能使用使用您的板条箱来创建隐式Send
的类型,并且在其实现中的任何地方均不包含不安全的代码,并且将其设置为不安全的只需为其实现ThreadThing
即可-在这种情况下,您可以将ThreadThing
设置为Send的东西没有实现ThreadThing
".
If it would be possible for someone using your crate to make a type that is implicitly Send
, contains no unsafe code in its implementation anywhere, and make it unsafe just by implementing ThreadThing
for it -- in that case, you would make ThreadThing
an unsafe trait
to indicate that there is unsafe code somewhere that relies on an invariant that can't be described in the type system: the invariant "Things that are Send
don't implement ThreadThing
".
如果很可能对于实现ThreadThing
的类型手动实现Send
只是不安全的-在这种情况下,您无需执行任何操作,因为
If, as is more likely, it's only unsafe to implement Send
manually for a type that implements ThreadThing
-- in that case, you don't need to do anything, because manually implementing Send
is unsafe already. If an implementor of ThreadThing
decides to manually implement Send
, they take on the burden of guaranteeing not only their own invariants, but also ThreadThing
's.
这篇关于我可以定义必须执行`!Send`的特征吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!