Rust 中的 auto trait 是什么? [英] What is an auto trait in Rust?

查看:113
本文介绍了Rust 中的 auto trait 是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图解决Trait bound Sized 中描述的问题对 Sized trait 不满意,我发现以下代码给出了以下错误:

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:

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.

什么是 Rust 中的自动特征,它与非自动特征有何不同?

What is an auto trait in Rust and how does it differ from a non-auto trait?

推荐答案

auto trait 是名为1 选择加入的新名称,内置特性 (OIBIT).

An auto trait is the new name for the terribly named1 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:

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

熟悉的例子包括Send同步:

Familiar examples include Send and Sync:

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

更多信息可在不稳定的书.

1 这些特征既不是选择加入(它们是选择退出)也不是内置的(使用 nightly 的用户代码可能会使用它们).在他们名字的 5 个词中,有 4 个是彻头彻尾的谎言.

1 These traits are neither opt-in (they are opt-out) nor necessarily built-in (user code using nightly may use them). Of the 5 words in their name, 4 were outright lies.

这篇关于Rust 中的 auto trait 是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆