2017-03-18 37 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來完成此操作。您還可以生成一次性函數來表達您的特質界限。

相關問題