2017-03-18 56 views
2
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似乎没有公开它实现的特征。我如何检查Ty是否实现了特定的特性?这目前不可能吗?

回答

2

看看你的代码的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来完成此操作。您还可以生成一次性函数来表达您的特质界限。

相关问题