Last active
August 4, 2023 03:25
-
-
Save w33ladalah/0554404a6b140187145004afb0caf198 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// My answer for Exercism's Clock exercise | |
use std::fmt; | |
#[derive(PartialEq)] | |
pub struct Clock { | |
hours: i32, | |
minutes: i32, | |
} | |
impl Clock { | |
pub fn new(hours: i32, minutes: i32) -> Self { | |
Self { | |
hours, | |
minutes, | |
} | |
} | |
pub fn add_minutes(&self, minutes: i32) -> Self { | |
let new_minutes = self.minutes + minutes; | |
Self{ | |
hours: self.hours, | |
minutes: new_minutes | |
} | |
} | |
pub fn to_string(&self) -> String { | |
let minutes_str = match self.minutes { | |
x if x < 10 && x >= 0 => format!("0{}", self.minutes), | |
_ => format!("{}", self.minutes), | |
}; | |
let hours_str = match self.hours { | |
x if x < 10 && x >= 0 => format!("0{}", self.hours), | |
_ => format!("{}", self.hours), | |
}; | |
format!("{}:{}", hours_str, minutes_str) | |
} | |
} | |
impl fmt::Display for Clock { | |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | |
write!(f, "{}", self.to_string()) | |
} | |
} | |
impl fmt::Debug for Clock { | |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | |
write!(f, "{}", &self.to_string()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment