gpt4 book ai didi

rust - Rust 中的自动特性是什么?

转载 作者:行者123 更新时间:2023-11-29 07:41:58 25 4
gpt4 key购买 nike

尝试解决 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

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

最佳答案

auto trait 是名称非常糟糕的1 opt-in,built-in 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 { }

有关更多信息,请参阅 Unstable Book .


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

关于rust - Rust 中的自动特性是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49710852/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com