Abstract
I am a beginner of Rust language. As my practice I want to create simple train reservation system.
I know little about the "best practice" in Rust, so I want some advises in my code. In terms of the function there are much luck to improve, but I want advises about how to write codes "in Rust".
Code structure
reservation
├── Cargo.lock
├── Cargo.toml
├── src
│ ├── lib.rs
│ ├── main.rs
│ └── reserve_request
│ └── mod.rs
└── target
My codes
lib.rs
pub mod reserve_request;
reserve_request/mod.rs
use std::collections::HashMap;
#[derive(PartialEq, Eq, Hash)]
pub struct Stations<'a> {
pub start: &'a str,
pub destination: &'a str,
}
pub struct Request<'a> {
pub start: &'a str,
pub destination: &'a str,
pub time: &'a str,
pub time_kind: &'a str,
}
impl<'a> Request<'a> {
pub fn reserve(&self, timetable: HashMap<Stations, &[&str]>) -> bool {
let st = Stations {
start: self.start,
destination: self.destination,
};
let times = timetable.get(&st);
let default: &[&str] = &[];
let result = match times {
Some(r) => r,
None => default,
};
for t in result {
if *t == self.time {
return true;
}
}
false
}
pub fn is_valid(&self) -> bool {
if self.start == "" {
println!("You need to determine start point");
return false;
} else if self.destination == "" {
println!("You need to determine destination");
return false;
} else if self.start == self.destination {
println!("Invalid. The start point and destication is same");
} else if self.time == "" && self.time_kind != "" {
println!("Invalid time specification");
return false;
}
true
}
}
main.rs
use reserve::reserve_request;
use std::collections::HashMap;
fn main() {
//TODO: save time table in the json file
let time: &[&str] = &["12:00", "14:00", "18:00", "19:00"];
let mut stations = HashMap::new();
stations.insert(
reserve_request::Stations {
start: "Tokyo",
destination: "Kyoto",
},
time,
);
let request = reserve_request::Request {
start: "Tokyo",
destination: "Kyoto",
time: "18:00",
time_kind: "start",
};
if request.is_valid() && request.reserve(stations) {
println!("Succeed in reserving that train");
} else {
println!("Failed to reserved that train");
}
}
What I want to know especially
In main.rs, to make a value of the
HashMap
(type&[&str]
), I definetime
variable and insert into HashMap. I feel it is redundant but I do not know how to deal with.Similar to above, in mod.rs, I make
default
variable for using in match clause only.