テストケース: リスト

構造体のそれぞれの要素を別々に扱うfmt::Displayを実装するのはトリッキーです。というのも、それぞれのwrite!が別々のfmt::Resultを生成するためです。適切に処理するためには すべての resultに対して処理を書かなくてはなりません。このような場合は?演算子を使用するのが適当です。

以下のように?write!に対して使用します。

// Try `write!` to see if it errors. If it errors, return
// the error. Otherwise continue.
// `write!`を実行し、エラーが生じた場合はerrorを返す。そうでなければ実行を継続する。
write!(f, "{}", value)?;

Alternatively, you can also use the try! macro, which works the same way. This is a bit more verbose and no longer recommended, but you may still see it in older Rust code. Using try! looks like this:

try!(write!(f, "{}", value));

?を使用できれば、Vec用のfmt::Displayはより簡単に実装できます。

use std::fmt; // Import the `fmt` module.

// Define a structure named `List` containing a `Vec`.
// `Vec`を含む`List`という名の構造体を定義
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`.
        // `v`を介して`vec`をイテレーションし、同時にカウントを
        // `enumerate`で取得する
        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.
        // 開きっぱなしのブラケットを閉じて、`fmt::Result`の値を返す。
        write!(f, "]")
    }
}

fn main() {
    let v = List(vec![1, 2, 3]);
    println!("{}", v);
}

演習

上記のプログラムを変更して、ベクタの各要素のインデックスも表示するようにしてみましょう。変更後の出力は次のようになります。

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

参照

for, ref, Result, 構造体, ?, vec!

関連キーワード:  fmt, Result, テストケース, 関数, vec, エラー, Rust, Example, By, List