use std::fmt; use std::str; #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Serialize, Deserialize)] pub enum Ship { Battleship, Carrier, Cruiser, Destroyer, Submarine } impl fmt::Display for Ship { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use Ship::*; f.write_str( match self { &Battleship => "Battleship", &Carrier => "Carrier", &Cruiser => "Cruiser", &Destroyer => "Destroyer", &Submarine => "Submarine" } ) } } impl str::FromStr for Ship { type Err = String; fn from_str(s: &str) -> Result { use Ship::*; match s { "Battleship" => Ok(Battleship), "Carrier" => Ok(Carrier), "Cruiser" => Ok(Cruiser), "Destroyer" => Ok(Destroyer), "Submarine" => Ok(Submarine), _ => Err(String::from("ship type is not known")) } } } impl Ship { pub fn length(&self) -> u16 { use Ship::*; match self { &Battleship => 4, &Carrier => 5, &Cruiser => 3, &Destroyer => 2, &Submarine => 3 } } pub fn all_types() -> Vec { use Ship::*; vec!( Battleship, Carrier, Cruiser, Destroyer, Submarine ) } }