【问题标题】:What is an auto trait in Rust?Rust 中的自动特征是什么?
【发布时间】:2018-09-17 13:09:13
【问题描述】:

试图解决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 中的自动 trait,它与非自动 trait 有何不同?

【问题讨论】:

  • 我认为这将是任何自动实现的特征,Sized 肯定是这种情况,但我想知道这是否适用于 SendSync...
  • @MatthieuM。我认为Sized 可能比SendSync 更特别...

标签: rust


【解决方案1】:

auto trait 是名为1opt-in, built-in trait (OIBIT) 的新名称。 p>

这是一个不稳定的特性,每个类型都会自动实现特征,除非它们选择退出或包含不实现特征的值:

#![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 个是彻头彻尾的谎言。

【讨论】:

  • 我完全同意此功能的名称令人困惑。它只是让我失望了(我试图选择 out of Send)。谢谢你的解释。
  • 此功能的当前状态是什么?我有一个特征 Render 应该由所有实现 Display 的东西来实现。
  • @nuiun:我发现了如何做到这一点:impl&lt;D: Display&gt; Render for D {...}
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-03
  • 1970-01-01
  • 2021-06-07
  • 2010-11-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多