Skip to content
Snippets Groups Projects
Commit d6aa69ae authored by Michael Hauspie's avatar Michael Hauspie
Browse files

Replace ConvertToString by std::fmt::Display

parent 0c1b7cec
No related branches found
No related tags found
No related merge requests found
trait ConvertToString {
/// Returns a string representation of self
fn to_string(&self) -> String;
}
#[derive(Clone, Copy, Debug, PartialEq)] #[derive(Clone, Copy, Debug, PartialEq)]
enum Square { enum Square {
Empty, Empty,
...@@ -10,12 +5,12 @@ enum Square { ...@@ -10,12 +5,12 @@ enum Square {
Circle, Circle,
} }
impl ConvertToString for Square { impl std::fmt::Display for Square {
fn to_string(&self) -> String { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self { match self {
Square::Empty => String::from("."), Square::Empty => write!(f, "."),
Square::Cross => String::from("X"), Square::Cross => write!(f, "X"),
Square::Circle => String::from("O"), Square::Circle => write!(f, "O"),
} }
} }
} }
...@@ -34,28 +29,23 @@ impl Board { ...@@ -34,28 +29,23 @@ impl Board {
/// Display the board to standard output /// Display the board to standard output
fn display(&self) { fn display(&self) {
println!("{}", self.to_string()); println!("{}", self);
} }
} }
impl ConvertToString for Board { impl std::fmt::Display for Board {
fn to_string(&self) -> String { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut out = String::new();
for row in 0..3 { for row in 0..3 {
out.push_str( writeln!(f, " {} | {} | {}",
format!( self.board[row * 3],
" {} | {} | {}", self.board[row * 3 + 1],
self.board[row * 3].to_string(), self.board[row * 3 + 2],
self.board[row * 3 + 1].to_string(), )?;
self.board[row * 3 + 2].to_string()
)
.as_str(),
);
if row == 0 || row == 1 { if row == 0 || row == 1 {
out.push_str("\n---+---+---\n"); writeln!(f, "---+---+---")?;
} }
} }
out Ok(())
} }
} }
...@@ -96,20 +86,21 @@ mod tests { ...@@ -96,20 +86,21 @@ mod tests {
---+---+--- ---+---+---
. | . | . . | . | .
---+---+--- ---+---+---
. | . | ."; . | . | .
assert_eq!(expected, Board::new().to_string()); ";
assert_eq!(expected, format!("{}", Board::new()));
} }
#[test] #[test]
fn empty_square_to_string_dot() { fn empty_square_to_string_dot() {
assert_eq!(".", Square::Empty.to_string()); assert_eq!(".", format!("{}", Square::Empty));
} }
#[test] #[test]
fn cross_square_to_string_x() { fn cross_square_to_string_x() {
assert_eq!("X", Square::Cross.to_string()); assert_eq!("X", format!("{}", Square::Cross));
} }
#[test] #[test]
fn circle_square_to_string_big_o() { fn circle_square_to_string_big_o() {
assert_eq!("O", Square::Circle.to_string()); assert_eq!("O", format!("{}", Square::Circle));
} }
} }
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment