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)]
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));
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment