I am getting started with rust. To get familiar with the language I implemented a datetime library:
main.rs
mod datetime;
use datetime::DateTime;
use datetime::Date;
use datetime::Time;
fn main() {
let date_time = DateTime::create(2022u16, 09, 17, 02, 53, 00);
println!("Datetime: {}", date_time);
println!("Date: {}", date_time.date);
println!("Time: {}", date_time.time);
let date = Date::new(2022u16, 09, 17);
println!("Date: {}", date);
let time = Time::new(03, 51, 00);
println!("Time: {}", time);
}
datetime.rs
use std::fmt;
mod date;
pub use self::date::Date;
mod time;
pub use self::time::Time;
pub struct DateTime {
pub date: Date,
pub time: Time
}
impl DateTime {
pub fn new(date: impl Into<Date>, time: impl Into<Time>) -> DateTime {
DateTime { date: date.into(), time: time.into() }
}
pub fn create(
year: impl Into<u16>,
month: impl Into<u8>,
day: impl Into<u8>,
hour: impl Into<u8>,
minute: impl Into<u8>,
second: impl Into<u8>
) -> DateTime {
DateTime::new(Date::new(year, month, day), Time::new(hour, minute, second))
}
pub fn isoformat(&self) -> String {
format!("{}T{}", self.date.isoformat(), self.time.isoformat())
}
}
impl fmt::Display for DateTime {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.isoformat())
}
}
datetime/date.rs
use std::fmt;
pub struct Date {
pub year: u16,
pub month: u8,
pub day: u8
}
impl Date {
pub fn new(year: impl Into<u16>, month: impl Into<u8>, day: impl Into<u8>) -> Date {
Date { year: year.into(), month: month.into(), day: day.into() }
}
pub fn isoformat(&self) -> String {
format!("{:0>4}-{:0>2}-{:0>2}", self.year, self.month, self.day)
}
}
impl fmt::Display for Date {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.isoformat())
}
}
datetime/time.rs
use std::fmt;
pub struct Time {
pub hour: u8,
pub minute: u8,
pub second: u8
}
impl Time {
pub fn new(hour: impl Into<u8>, minute: impl Into<u8>, second: impl Into<u8>) -> Time {
Time { hour: hour.into(), minute: minute.into(), second: second.into() }
}
pub fn isoformat(&self) -> String {
format!("{:0>2}:{:0>2}:{:0>2}", self.hour, self.minute, self.second)
}
}
impl fmt::Display for Time {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.isoformat())
}
}
Since I'm completely new to rust, I'd like to have feedback on code style and proper use of language concepts.