Rust by Example中文

1.2.2.1 Testcase: List

Implementing fmt::Display for a structure where the elements must each be handled sequentially is tricky. The problem is that each write! generates a fmt::Result. Proper handling of this requires dealing with all the results. Rust provides the try! macro for exactly this purpose.

Using try! on write! looks like this:

// Try `write!` to see if it errors. If it errors, return
// the error. Otherwise continue.
try!(write!(f, "{}", value));

With try! available, implementing fmt::Display for a Vec is straightforward:

use std::fmt; // Import the `fmt` module. // Define a structure named `List` containing a `Vec`. struct List(Vec<i32>); 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; try!(write!(f, "[")); // Iterate over `vec` in `v` while enumerating the iteration // count in `count`. for (count, v) in vec.iter().enumerate() { // For every element except the first, add a comma // before calling `write!`. Use `try!` to return on errors. if count != 0 { try!(write!(f, ", ")); } try!(write!(f, "{}", v)); } // Close the opened bracket and return a fmt::Result value write!(f, "]") } } fn main() { let v = List(vec![1, 2, 3]); println!("{}", v); }

See also

for, ref, Result, struct, try!, and vec!