簡體   English   中英

impl不引用此板條箱中定義的任何類型

[英]the impl does not reference any types defined in this crate

在我的一個結構Struct1有一個類型為time::Tm的字段。 在代碼中的某個位置,該結構的實例從json字符串解碼為Struct1的實例。

json::decode(&maybe_struct1)

剛開始我遇到一個錯誤,說to_json isn't implemented for time::Tm 所以我實現了它:

impl json::ToJson for time::Tm {
  fn to_json(&self) -> json::Json {
    let mut d = BTreeMap::new();
    d.insert("tm_sec".to_string(), self.tm_sec.to_json());
    d.insert("tm_min".to_string(), self.tm_min.to_json());
    //..............

現在它說

error: the impl does not reference any types defined in this crate; only traits defined in the current crate can be implemented for arbitrary types  [E0117]

我發現這是版本1之前的錯誤。但是仍然嗎? 如果沒有,我該如何解決?

這不是錯誤。 當你實現定義的任何性狀或所涉及的類型特征的語言要求。 如果您既未實現,則不允許這樣做。

如果沒有,其他人也有可能同時time::Tm實現json::ToJson ,突然編譯器不知道要使用哪個代碼。

解決此問題的最簡單方法是將time::Tm包裝為新類型,如下所示:

struct TmWrap(time::Tm);

現在,因為定義了這個類型,你可以實現json::ToJson就可以了。 這確實意味着您必須不斷地包裝/解開Tm ,但是唯一的替代方法是為整個包含的Struct1類型實現ToJson ,這可能還要做更多的工作。

這不是錯誤-它是功能。 真。 要實現特征,以下任何陳述必須為真:

  • 類型在此模塊中聲明
  • 特質在此模塊中聲明

否則得到E0117 您可以使用rustc --explain E0117找到更多信息:

該錯誤表明違反了Rust的一項孤立特征規則。 該規則禁止在以下情況下實施任何外來特性(在另一個板條箱中定義的特性)

  • 實現特質的類型是外國的
  • 傳遞給特征的所有參數(如果有的話)也是外來的。

這是此錯誤的一個示例:

 impl Drop for u32 {} 

為了避免這種錯誤,請確保impl引用了至少一個本地類型:

 pub struct Foo; // you define your type in your crate impl Drop for Foo { // and you can implement the trait on it! // code of trait implementation here } impl From<Foo> for i32 { // or you use a type from your crate as // a type parameter fn from(i: Foo) -> i32 { 0 } } 

或者,在本地定義一個特征,然后實現該特征:

 trait Bar { fn get(&self) -> usize; } impl Bar for u32 { fn get(&self) -> usize { 0 } } 

有關孤立規則設計的信息,請參閱RFC 1023

編輯:

為了實現您想要的,您有兩種解決方案:

  • 在您的整個類型上實現ToJson

      impl json::ToJson for Struct1 { … } 
  • 創建一個包裝類型struct TmWrapper(time::Tm); 並實現FromToJson 2個特點。

編輯2:

逐步說明:

  1. 這是您想要實現的: http : //is.gd/6UF3jd
  2. 解決方案:

正是上述錯誤代碼的說明中所描述的內容。

因此,您看到-必須在當前單元中聲明trait或struct中的至少一個,以允許在給定類型上實現trait。 在您的情況下,它們都是外部類型,這就是Rust的預防方法。 如果您想實現類似的目標,則需要使用如上所述的一些技巧。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM