测试用例:列表
为元素实现 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); }