[英]Can I define a trait whose implementations must be `!Send`?
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. 将特征标记为!Send
就足够了,但是Rust似乎没有允许我。
Is it possible? 可能吗?
Example ( playground ): 示例( 操场 ):
#![feature(optin_builtin_traits)]
// This is a syntax error
//trait ThreadThing : !Send {}
// This doesn't work either
trait ThreadThing { }
impl !Send for ThreadThing {}
No, you can't make !Send
a condition of ThreadThing
. 不,您不能!Send
ThreadThing
条件。 The compiler just doesn't support that kind of logic. 编译器只是不支持这种逻辑。
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
". 如果某人可能使用您的板条箱创建一个隐式Send
的类型,则在其实现中的任何地方均不包含不安全的代码,并仅通过ThreadThing
实现ThreadThing
使其不安全 -在这种情况下,您将使ThreadThing
unsafe trait
,表明某个地方存在不安全代码,该代码依赖于类型系统中无法描述的不变式:不变式“ Send
事物未实现ThreadThing
”。
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 . 如果很可能对于实现ThreadThing
的类型手动实现Send
只是不安全的-在这种情况下,您无需执行任何操作,因为手动实现Send
已经不安全了 。 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. 如果ThreadThing
的实现者决定手动实现Send
,则他们不仅要保证自己的不变式,还要ThreadThing
的不变性。
The answer is: yes, you can, under some very specific conditions. 答案是:是的,您可以在某些非常特定的条件下进行操作。 Whether you should need to do this is another matter. 是否需要执行此操作是另一回事。
You can define a negative trait implementation for another trait if the trait you are negating is: 如果要否定的特征是,则可以为另一个特征定义否定特征实现:
So the following will work ( playground ): 因此,以下将工作( 操场 ):
#![feature(optin_builtin_traits)]
auto trait Scary {}
trait ThreadThing { }
impl !Scary for ThreadThing {}
But it would not work if you were trying to do: 但是,如果您尝试这样做,将无法正常工作:
impl !Send for ThreadThing {}
Or if Scary
was not an auto-trait. 或者,如果Scary
不是自动特征。
Note however that, in general it should not be necessary to mark a trait !Send
in this way. 但是请注意,通常不必标记特征!Send
以这种方式!Send
。 The concrete implementations of the trait will be marked Send
or !Send
by the Rust compiler based upon the contents of the implementing struct. 特质的具体实现将由Rust编译器根据实现结构的内容标记为Send
或!Send
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.