是否可以检查字段是否实现了自定义派生的特征?

时间:2017-03-18 10:20:48

标签: rust

struct Foo;

#[derive(Clone)]
struct Bar {
    f: Foo,
}

fn main() {}

Playground

这导致

error[E0277]: the trait bound `Foo: std::clone::Clone` is not satisfied
 --> <anon>:5:5
  |
5 |     f: Foo,
  |     ^^^^^^ the trait `std::clone::Clone` is not implemented for `Foo`
  |
  = note: required by `std::clone::Clone::clone`

如果所有类型的字段都实现了克隆,则只能派生Clone。我想做同样的事情。

Field似乎没有暴露它实现的特征。我如何检查Type是否实现了特定的特征?这目前不可能吗?

1 个答案:

答案 0 :(得分:3)

查看代码的expanded version

#![feature(prelude_import)]
#![no_std]
#[prelude_import]
use std::prelude::v1::*;
#[macro_use]
extern crate std as std;
struct Foo;

struct Bar {
    f: Foo,
}
#[automatically_derived]
#[allow(unused_qualifications)]
impl ::std::clone::Clone for Bar {
    #[inline]
    fn clone(&self) -> Bar {
        match *self {
            Bar { f: ref __self_0_0 } => Bar { f: ::std::clone::Clone::clone(&(*__self_0_0)) },
        }
    }
}

fn main() {}

所有这一切都是调用一个具有特征限制的函数,传入参数。这很有用,因为无论如何都需要递归调用clone。这样可以“免费”检查。

如果您不需要调用相关特征,您仍然可以执行与enforce that an argument implements a trait at compile time类似的操作。 Eq通过实施hidden function on the trait来实现此目的。您还可以生成表达特征限制的一次性函数。

相关问题