测试用例:列表

为一个结构体实现 fmt::Display,其中元素必须按顺序处理,这很棘手。问题是每个 write! 都会生成一个 fmt::Result。正确处理这个问题需要处理所有的结果。Rust 提供了 ? 运算符来专门实现此目的。

write! 上使用 ? 看起来像这样

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

有了 ?,为一个 Vec 实现 fmt::Display 就很简单了

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 {
        // Extract the value using tuple indexing,
        // and create a reference to `vec`.
        let vec = &self.0;

        write!(f, "[")?;

        // Iterate over `v` in `vec` while enumerating the iteration
        // count in `count`.
        for (count, v) in vec.iter().enumerate() {
            // For every element except the first, add a comma.
            // Use the ? operator to return on errors.
            if count != 0 { write!(f, ", ")?; }
            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);
}

活动

尝试更改程序,使向量中每个元素的索引也被打印出来。新的输出应该如下所示

[0: 1, 1: 2, 2: 3]

另请参阅

for, ref, Result, struct, ?, 和 vec!