繁体   English   中英

我如何得出另一个特征的特征?

[英]How do I derive a trait for another trait?

我有一个结构,包含一个像这样的特征对象成员:

trait Contract {}

#[derive(Debug)]
struct Foo {
    x: Box<Contract>,
}

我希望该结构派生Debug ,但编译器不喜欢它:

error[E0277]: `Contract + 'static` doesn't implement `std::fmt::Debug`
 --> src/main.rs:5:5
  |
5 |     x: Box<Contract>,
  |     ^^^^^^^^^^^^^^^^ `Contract + 'static` cannot be formatted using `:?`; add `#[derive(Debug)]` or manually implement `std::fmt::Debug`
  |
  = help: the trait `std::fmt::Debug` is not implemented for `Contract + 'static`
  = note: required because of the requirements on the impl of `std::fmt::Debug` for `std::boxed::Box<Contract + 'static>`
  = note: required because of the requirements on the impl of `std::fmt::Debug` for `&std::boxed::Box<Contract + 'static>`
  = note: required for the cast to the object type `std::fmt::Debug`

我真的不确定如何解决这个问题。 我理解为什么编译器不能为特征实现Debug ,因为它不能告诉哪些类型会实现它,但同样的原因是让我不能手动为特征实现它(甚至不确定是否可能)。

什么是获得我想要的行为的好方法?

特征不能使用#[derive()]属性; 你需要手动实现它:

trait Contract {}

impl std::fmt::Debug for Contract {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}", "derp")
    }
}

由于trait对象丢失了有关类型( 类型擦除 )的信息,因此您可以使用Contract实现的函数,但您无法访问底层类型或其特定的Debug实现。

但是,如果使Contract依赖于Debug特性,则确保其所有实现者也必须实现Debug

trait Contract: std::fmt::Debug {}

您将能够为#[derive(Debug)] foo #[derive(Debug)]而无需手动实现Debug for Contract

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM