Выбрать главу

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 ? operator for exactly this purpose.

Using ? on write! looks like this:

// Try `write!` to see if it errors. If it errors, return

// the error. Otherwise continue.

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

With ? 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 {

// 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);

}

הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Try changing the program so that the index of each element in the vector is also printed. The new output should look like this:

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

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

We've seen that formatting is specified via a format string:

   • format!("{}", foo) -> "3735928559"

   • format!("0x{:X}", foo) -> "0xDEADBEEF"

   • format!("0o{:o}", foo) -> "0o33653337357"

The same variable (foo) can be formatted differently depending on which argument type is used: X vs o vs unspecified.

This formatting functionality is implemented via traits, and there is one trait for each argument type. The most common formatting trait is Display, which handles cases where the argument type is left unspecified: {} for instance.

use std::fmt::{self, Formatter, Display};

struct City {

name: &'static str,

// Latitude

lat: f32,

// Longitude

lon: f32,

}

impl Display for City {

// `f` is a buffer, and this method must write the formatted string into it

fn fmt(&self, f: &mut Formatter) -> fmt::Result {

let lat_c = if self.lat >= 0.0 { 'N' } else { 'S' };

let lon_c = if self.lon >= 0.0 { 'E' } else { 'W' };

// `write!` is like `format!`, but it will write the formatted string

// into a buffer (the first argument)

write!(f, "{}: {:.3}°{} {:.3}°{}",

self.name, self.lat.abs(), lat_c, self.lon.abs(), lon_c)

}

}

#[derive(Debug)]

struct Color {

red: u8,

green: u8,

blue: u8,

}

fn main() {

for city in [

City { name: "Dublin", lat: 53.347778, lon: -6.259722 },

City { name: "Oslo", lat: 59.95, lon: 10.75 },

City { name: "Vancouver", lat: 49.25, lon: -123.1 },

].iter() {

println!("{}", *city);

}

for color in [

Color { red: 128, green: 255, blue: 90 },

Color { red: 0, green: 3, blue: 254 },

Color { red: 0, green: 0, blue: 0 },

].iter() {

// Switch this to use {} once you've added an implementation

// for fmt::Display.

println!("{:?}", *color);

}

}

הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

You can view a full list of formatting traits and their argument types in the std::fmt documentation.

Add an implementation of the fmt::Display trait for the Color struct above so that the output displays as: