Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Testcase: List

Реалізація 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)?;

З ? реалізувати fmt::Display для Vec просто:

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 {
        // Create a reference to the Vec<i32> stored in the List struct.
        let vec = &self.0;

        write!(f, "[")?;

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