2014-11-13 20 views
1

我想實現我的二叉樹的core :: fmt :: Show。這是我的實現代碼:試圖執行core :: fmt ::顯示

impl<T: PartialEq + PartialOrd + Show> Show for Node<T> 
{ 
    fn fmt(&self, f: &mut Formatter) -> Result<(), &str> 
    { 
     match self.left { 
      Some(ref x) => {x.fmt(f);}, 
      None => {} 
     }; 
     match self.value { 
      Some(ref x) => { 
       write!(f, "{}", x.to_string().as_slice()); 
      }, 
      None => {} 
     }; 
     match self.right { 
      Some(ref x) => {x.fmt(f);}, 
      None => {} 
     }; 
     Ok(()) 
    } 
} 

但是,編譯器會引發以下錯誤:

Compiling binary_tree v0.0.1 (file:///home/guillaume/projects/binary_tree) src/binary_tree.rs:60:2: 77:3 error: method fmt has an incompatible type for trait: expected enum core::fmt::FormatError, found &-ptr [E0053] src/binary_tree.rs:60 fn fmt(&self, f: &mut Formatter) -> Result<(), &str> src/binary_tree.rs:61 { src/binary_tree.rs:62 match self.left { src/binary_tree.rs:63 Some(ref x) => {x.fmt(f);}, src/binary_tree.rs:64 None => {} src/binary_tree.rs:65 };

我不明白爲什麼。完整的代碼可以找到here。有關我的代碼的任何意見,歡迎。

回答

4

該錯誤是告訴您fmt不具有它期望的類型,特別是它發現一個& -ptr(即,STR &)其中應該有一個FormatError的方法。

改變方法簽名,這將解決您的編譯錯誤:

fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::FormatError> 

我已經派人在GitHub上拉要求,使這一變化(以及還修復您的測試,所以我可以驗證它的工作)

+1

最好使用'fmt :: Result'而不是顯式的'Result <(),fmt :: FormatError>'。這就是Show特質本身的作用。 –

+0

非常感謝您花時間更正我的代碼! – Moebius

0

@McPherrinM提出的答案正在解決這個錯誤,但rustc仍然會引發一些警告。這其中的代碼使用刪除警告:

fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::FormatError> 
{ 
    let mut result = Ok(()); 
    match self.left { 
     Some(ref x) => { 
      result = result.and(x.fmt(f)); 
     }, 
     None => {;} 
    }; 
    match self.value { 
     Some(ref x) => { 
      result = result.and(write!(f, "{}", x.to_string().as_slice())); 
     }, 
     None => {;} 
    }; 
    match self.right { 
     Some(ref x) => { 
      result = result.and(x.fmt(f)); 
     }, 
     None => {;} 
    }; 
    result 
} 

這是所有關於確保您轉發錯誤消息此函數的調用者。

問:

如果錯誤發生時,該功能將遞歸地進行,如果超過一個錯誤信息彈出,最後一個一個將覆蓋舊的一個。這不正確嗎?