diff --git a/src/main.rs b/src/main.rs index f0cf8f50c326be89d5117ad43a98b246f2405836..2c3283225597fab9e51ab46587553255d925f169 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,8 +1,3 @@ -trait ConvertToString { - /// Returns a string representation of self - fn to_string(&self) -> String; -} - #[derive(Clone, Copy, Debug, PartialEq)] enum Square { Empty, @@ -10,12 +5,12 @@ enum Square { Circle, } -impl ConvertToString for Square { - fn to_string(&self) -> String { +impl std::fmt::Display for Square { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - Square::Empty => String::from("."), - Square::Cross => String::from("X"), - Square::Circle => String::from("O"), + Square::Empty => write!(f, "."), + Square::Cross => write!(f, "X"), + Square::Circle => write!(f, "O"), } } } @@ -34,28 +29,23 @@ impl Board { /// Display the board to standard output fn display(&self) { - println!("{}", self.to_string()); + println!("{}", self); } } -impl ConvertToString for Board { - fn to_string(&self) -> String { - let mut out = String::new(); +impl std::fmt::Display for Board { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { for row in 0..3 { - out.push_str( - format!( - " {} | {} | {}", - self.board[row * 3].to_string(), - self.board[row * 3 + 1].to_string(), - self.board[row * 3 + 2].to_string() - ) - .as_str(), - ); + writeln!(f, " {} | {} | {}", + self.board[row * 3], + self.board[row * 3 + 1], + self.board[row * 3 + 2], + )?; if row == 0 || row == 1 { - out.push_str("\n---+---+---\n"); + writeln!(f, "---+---+---")?; } } - out + Ok(()) } } @@ -96,20 +86,21 @@ mod tests { ---+---+--- . | . | . ---+---+--- - . | . | ."; - assert_eq!(expected, Board::new().to_string()); + . | . | . +"; + assert_eq!(expected, format!("{}", Board::new())); } #[test] fn empty_square_to_string_dot() { - assert_eq!(".", Square::Empty.to_string()); + assert_eq!(".", format!("{}", Square::Empty)); } #[test] fn cross_square_to_string_x() { - assert_eq!("X", Square::Cross.to_string()); + assert_eq!("X", format!("{}", Square::Cross)); } #[test] fn circle_square_to_string_big_o() { - assert_eq!("O", Square::Circle.to_string()); + assert_eq!("O", format!("{}", Square::Circle)); } }