代码之家  ›  专栏  ›  技术社区  ›  uconnboi

特质名称后的特质是什么意思?

  •  0
  • uconnboi  · 技术社区  · 2 年前

    我在阅读有关锈病的文章时,偶然发现了这个特质定义:

    trait Enchanter: std::fmt::Debug {
        ...
    }
    

    由此我了解到,这种特质的名称是 Enchanter ,但我不明白 std::Format:Debug 部分暗示,因为它也是一种特质(我认为)。

    1 回复  |  直到 2 年前
        1
  •  3
  •   Chayim Friedman    2 年前

    这是在声明 supertrait . 相当于:

    trait Enchanter
    where
        Self: std::fmt::Debug,
    {
    }
    

    简而言之,它需要任何想要实现的类型 Enchanter 也要实施 std::fmt::Debug . 否则 an error will be raised :

    error[E0277]: `S` doesn't implement `Debug`
     --> src/lib.rs:4:6
      |
    4 | impl Enchanter for S {}
      |      ^^^^^^^^^ `S` cannot be formatted using `{:?}`
      |
      = help: the trait `Debug` is not implemented for `S`
      = note: add `#[derive(Debug)]` to `S` or manually `impl Debug for S`
    note: required by a bound in `Enchanter`
     --> src/lib.rs:1:18
      |
    1 | trait Enchanter: std::fmt::Debug {}
      |                  ^^^^^^^^^^^^^^^ required by this bound in `Enchanter`