From b8668163e12b0cda4e13ea8bd841bea7372ea16d Mon Sep 17 00:00:00 2001 From: Jon Janzen Date: Tue, 3 Nov 2020 18:24:04 -0700 Subject: [PATCH] supertrait --- src/main.rs | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/src/main.rs b/src/main.rs index c397617..414357f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,4 +1,5 @@ use std::ops::Add; +use std::fmt; #[derive(Debug, PartialEq)] struct Point { @@ -17,7 +18,6 @@ impl Add for Point { } } - #[derive(Debug, PartialEq)] struct Millimeters(u32); #[derive(Debug, PartialEq)] @@ -77,6 +77,28 @@ impl Animal for Dog { } } + +trait OutlinePrint: fmt::Display { + fn outline_print(&self) { + let output = self.to_string(); + let len = output.len(); + + println!("{}", "*".repeat(len + 4)); + println!("*{}*", " ".repeat(len + 2)); + println!("* {} *", output); + println!("*{}*", " ".repeat(len + 2)); + println!("{}", "*".repeat(len + 4)); + } +} + +impl fmt::Display for Point { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "({}, {})", self.x, self.y) + } +} + +impl OutlinePrint for Point {} + fn main() { assert_eq!( Point { x: 1, y: 0 } + Point { x: 2, y: 3 }, @@ -94,4 +116,8 @@ fn main() { Wizard::fly(&person); println!("A baby dog is called a {}", ::baby_name()); + + let xy = Point { x: 344, y: 576 }; + xy.outline_print(); + println!("{}", Point {x: 34, y:45}) }