測試用例:列表
測試用例:列表
為元素實現 fmt::Display,必須按順序分彆處理的結構是棘手的。問題是,每一個 write! 生成 fmt::Result。妥善處理這需要處理所有的結果。 Rust 提供 try! 宏正是為這個目的。
用 try! 在 write! 看起來是這樣的:
// Try `write!` to see if it errors. If it errors, return
// the error. Otherwise continue.
try!(write!(f, "{}", value));
隨著try! 可用,實現 fmt::Display 讓 Vec 很簡單:
use std::fmt; // Import the `fmt` module. // Define a structure named `List` containing a `Vec`. struct List(Vec); impl fmt::Display for List { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // Dereference `self` and create a reference to `vec` // via destructuring. let List(ref vec) = *self; let len = vec.len(); // Save the vector length in `len`. // Iterate over `vec` in `v` while enumerating the iteration // count in `count`. for (count, v) in vec.iter().enumerate() { // For every element except the last, format `write!` // with a comma. Use `try!` to return on errors. if count < len - 1 { try!(write!(f, "{}, ", v)) } } // `write!` the last value without special formatting. write!(f, "{}", vec[len-1]) } } fn main() { let v = List(vec![1, 2, 3]); println!("{}", v); }