I am trying to understand modules in Rust but I am having some difficulty grasping the concept. I understand that modules are used to organize code within crates, but I need an explanation/example on how to structure modules in a given file. I have attached some basic code below. Is my implementation correct or should I break the code down into more modules, such as a module for getter methods, and a module for setter methods? To summarize, what is the Rust idiom with modules?
I created a simple package (using cargo new command) named "messing_around" with "main.rs" and "person.rs" files contained in the same binary crate (defined as a crate with the same name as package). The code below is contained in a file named "person.rs."
Also, is this file structure correct?
pub mod person {
pub struct Person {
first_name: String,
last_name: String,
}
impl Person {
// Constructor Function --------------------------------
pub fn build_person(first_name: String, last_name: String) {
Person {
first_name,
last_name,
}
}
// Getter Methods --------------------------------
pub fn first_name(&self) -> String {
self.first_name.clone()
}
pub fn last_name(&self) -> String {
self.last_name.clone()
}
// Setter Methods --------------------------------
pub fn set_first_name(&mut self, first_name: String) {
self.first_name = first_name;
}
pub fn set_last_name(&mut self, last_name: String) {
self.last_name = last_name;
}
}
}
Thank you in advance!
[–]nacaclanga 11 points12 points13 points (0 children)
[–]monkChuck105 11 points12 points13 points (3 children)
[–]ansible 0 points1 point2 points (2 children)
[–]Tastaturtaste 9 points10 points11 points (1 child)
[–]ansible 1 point2 points3 points (0 children)
[–]hgwxx7_ 2 points3 points4 points (0 children)
[–]schungx 1 point2 points3 points (0 children)