From 97491bfb1a0a1e5212b41c8b38e34ab76f22f1a8 Mon Sep 17 00:00:00 2001 From: Bassem Girgis Date: Sat, 17 Jul 2021 14:25:09 -0500 Subject: [PATCH] 3rd --- src/main.rs | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/src/main.rs b/src/main.rs index 8f430fd..ad535fa 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,49 @@ +use std::fmt; + +// use the automated debug as below +//#[derive(fmt::Debug)] +struct Vector2D { + x: isize, + y: isize, +} + +// Or write your own +impl fmt::Debug for Vector2D { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // The `f` value implements the `Write` trait, which is what the + // write! macro is expecting. Note that this formatting ignores the + // various flags provided to format strings. + write!(f, "My Vector2D debug({}, {})", self.x, self.y) + } +} + +// display cannot be automatically generated +impl fmt::Display for Vector2D { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // The `f` value implements the `Write` trait, which is what the + // write! macro is expecting. Note that this formatting ignores the + // various flags provided to format strings. + write!(f, "({}, {})", self.x, self.y) + } +} + +// Different traits allow different forms of output of a type. The meaning +// of this format is to print the magnitude of a vector. +impl fmt::Binary for Vector2D { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let magnitude: f64 = (self.x * self.x + self.y * self.y) as f64; + let magnitude = magnitude.sqrt(); + + // Respect the formatting flags by using the helper method + // `pad_integral` on the Formatter object. See the method + // documentation for details, and the function `pad` can be used + // to pad strings. + let decimals = f.precision().unwrap_or(3); + let string = format!("{:.*}", decimals, magnitude); + f.pad_integral(true, "", &string) + } +} + fn main() { // In general, the `{}` will be automatically replaced with any // arguments. These will be stringified. @@ -46,4 +92,10 @@ fn main() { // handling. This will not work. //println!("This struct `{}` won't print...", Structure(3)); // FIXME ^ Comment out this line. + + let myvector = Vector2D { x: 3, y: 4 }; + + println!("{}", myvector); // => "(3, 4)" + println!("{:?}", myvector); // => "Vector2D {x: 3, y:4}" + println!("{:10.3b}", myvector); // => " 5.000" }