[英]What is an auto trait in Rust?
Trying to solve the problem described in Trait bound Sized is not satisfied for Sized trait , I found the following code gives the following error:尝试解决Sized trait 中描述的Trait bound Sized 不满足的问题,我发现以下代码给出了以下错误:
trait SizedTrait: Sized {
fn me() -> Self;
}
trait AnotherTrait: Sized {
fn another_me() -> Self;
}
impl AnotherTrait for SizedTrait + Sized {
fn another_me() {
Self::me()
}
}
error[E0225]: only auto traits can be used as additional traits in a trait object
--> src/main.rs:9:36
|
9 | impl AnotherTrait for SizedTrait + Sized {
| ^^^^^ non-auto additional trait
But the Rust Book does not mention auto trait
at all.但是Rust Book根本没有提到
auto trait
。
What is an auto trait in Rust and how does it differ from a non-auto trait? Rust 中的自动特征是什么?它与非自动特征有何不同?
An auto trait is the new name for the terribly named 1 opt-in, built-in trait (OIBIT).自动特征是名称非常糟糕的1 opt-in, built-in trait (OIBIT) 的新名称。
These are an unstable feature where a trait is automatically implemented for every type unless they opt-out or contain a value that does not implement the trait:这些是不稳定的特性,其中 trait 会自动为每种类型实现,除非它们选择退出或包含未实现 trait 的值:
#![feature(optin_builtin_traits)]
auto trait IsCool {}
// Everyone knows that `String`s just aren't cool
impl !IsCool for String {}
struct MyStruct;
struct HasAString(String);
fn check_cool<C: IsCool>(_: C) {}
fn main() {
check_cool(42);
check_cool(false);
check_cool(MyStruct);
// the trait bound `std::string::String: IsCool` is not satisfied
// check_cool(String::new());
// the trait bound `std::string::String: IsCool` is not satisfied in `HasAString`
// check_cool(HasAString(String::new()));
}
Familiar examples include Send
and Sync
:熟悉的例子包括
Send
和Sync
:
pub unsafe auto trait Send { }
pub unsafe auto trait Sync { }
Further information is available in the Unstable Book .更多信息可在Unstable Book 中获得。
1 These traits are neither opt-in (they are opt-out) nor necessarily built-in (user code using nightly may use them). 1这些特征既不是选择加入的(它们是选择退出的)也不一定是内置的(使用 nightly 的用户代码可能会使用它们)。 Of the 5 words in their name, 4 were outright lies.
在他们名字中的 5 个词中,有 4 个是彻头彻尾的谎言。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.