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

Add ConvertToString trait

parent 8d759cce
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;
}
enum Square {
Empty,
Cross,
Circle,
}
impl ConvertToString for Square {
fn to_string(&self) -> String {
match self {
Square::Empty => String::from("."),
Square::Cross => String::from("X"),
Square::Circle => String::from("O"),
}
}
}
struct Board {
board: [Square; 9],
}
......@@ -14,8 +29,8 @@ impl Board {
Self {
board: [
Square::Empty,
Square::Cross,
Square::Circle,
Square::Empty,
Square::Empty,
Square::Empty,
Square::Empty,
Square::Empty,
......@@ -28,25 +43,25 @@ impl Board {
/// Display the board to standard output
fn display(&self) {
println!("{}", self.to_string());
}
}
impl ConvertToString for Board {
fn to_string(&self) -> String {
let mut out = String::new();
for row in 0..3 {
println!(
out.push_str(format!(
" {} | {} | {}",
square_to_char(&self.board[row * 3]),
square_to_char(&self.board[row * 3 + 1]),
square_to_char(&self.board[row * 3 + 2])
);
self.board[row * 3].to_string(),
self.board[row * 3 + 1].to_string(),
self.board[row * 3 + 2].to_string()
).as_str());
if row == 0 || row == 1 {
println!("---+---+---");
out.push_str("\n---+---+---\n");
}
}
}
}
fn square_to_char(s: &Square) -> char {
match s {
Square::Empty => '.',
Square::Cross => 'X',
Square::Circle => 'O',
out
}
}
......@@ -61,7 +76,7 @@ fn main() {
// A module where the tests are located, more on modules later
mod tests {
use super::*;
#[test]
fn should_pass() {
assert!(true);
......@@ -77,7 +92,6 @@ mod tests {
let board = Board::new();
for square in board.board {
// Cannot do that due to 'trait' issues, more on that
// later
// assert_eq!(square, Square::Empty);
......@@ -87,4 +101,27 @@ mod tests {
}
}
}
#[test]
fn empty_board_to_string() {
let expected = " . | . | .
---+---+---
. | . | .
---+---+---
. | . | .";
assert_eq!(expected, Board::new().to_string());
}
#[test]
fn empty_square_to_string_dot() {
assert_eq!(".", Square::Empty.to_string());
}
#[test]
fn cross_square_to_string_x() {
assert_eq!("X", Square::Cross.to_string());
}
#[test]
fn circle_square_to_string_big_o() {
assert_eq!("O", Square::Circle.to_string());
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment