Rust by Example | страница 6



>write!(f, "({}, {})", self.0, self.1)

>}

>}

>// Define a structure where the fields are nameable for comparison.

>#[derive(Debug)]

>struct Point2D {

>x: f64,

>y: f64,

>}

>// Similarly, implement `Display` for `Point2D`

>impl fmt::Display for Point2D {

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

>// Customize so only `x` and `y` are denoted.

>write!(f, "x: {}, y: {}", self.x, self.y)

>}

>}

>fn main() {

>let minmax = MinMax(0, 14);

>println!("Compare structures:");

>println!("Display: {}", minmax);

>println!("Debug: {:?}", minmax);

>let big_range = MinMax(-300, 300);

>let small_range = MinMax(-3, 3);

>println!("The big range is {big} and the small is {small}",

>small = small_range,

>big = big_range);

>let point = Point2D { x: 3.3, y: 7.2 };

>println!("Compare points:");

>println!("Display: {}", point);

>println!("Debug: {:?}", point);

>// Error. Both `Debug` and `Display` were implemented, but `{:b}`

>// requires `fmt::Binary` to be implemented. This will not work.

>// println!("What does Point2D look like in binary: {:b}?", point);

>}

>הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה

>XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

So, fmt::Display has been implemented but fmt::Binary has not, and therefore cannot be used. std::fmt has many such traits and each requires its own implementation. This is detailed further in std::fmt.

After checking the output of the above example, use the Point2D struct as a guide to add a Complex struct to the example. When printed in the same way, the output should be:

>Display: 3.3 + 7.2i

>Debug: Complex { real: 3.3, imag: 7.2 }

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.