Rust中的自动trait是什么?

37
尝试解决在Trait bound Sized is not satisfied for Sized trait中描述的问题时,我发现以下代码会产生以下错误:
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

然而,Rust Book中并没有提到auto trait

auto trait在Rust中是什么,与非自动trait有何不同?


我认为自动实现的任何特征都可以,对于 Sized 特征肯定是这样,但我想知道是否适用于 SendSync... - Matthieu M.
@MatthieuM。我认为Sized可能比SendSync还要特殊... - Shepmaster
1个回答

48

auto trait 是“选择加入,内置特性(OIBIT)”这个名字糟糕的旧称的新名称。

这是一项不稳定的功能,其中除非类型选择退出或包含不实现该特性的值,否则将自动实现每个类型的特性:

#![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()));
}

常见的例子包括SendSync

pub unsafe auto trait Send { }
pub unsafe auto trait Sync { }

更多信息请参考不稳定书籍


1这些特质既不是选择加入的(而是选择退出的),也不一定是内置的(使用夜间版的用户可能会使用它们)。在它们的名称中,有5个单词,其中4个是彻头彻尾的谎言。


1
我完全同意这个功能的名称很令人困惑。它让我感到困惑(我试图退出“发送”)。谢谢你的解释。 - Edd Barrett
这个功能目前的状态是什么?我有一个trait Render,应该由所有实现了Display的东西来实现。 - nuiun
@nuiun:我找到了如何实现这个:impl<D: Display> Render for D {...} - nuiun

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接