Search code examples
rustrust-cargo

How to import modules in deep directories in Rust?


I have a file in src/user/entity/user.rs with the following code:

pub struct User {
  name: String,
  email: String,
  age: i32,
  is_active: bool,
}

impl User {
  pub fn new(name: String, email: String, age: i32, is_active: bool) -> User {
    User {
      name,
      email,
      age,
      is_active
    }
  }

  pub fn get_name(&self) -> &str {
    &self.name
  }

  pub fn get_email(&self) -> &str {
    &self.email 
  }

  pub fn get_age(&self) -> i32 {
    self.age
  }

  pub fn is_active(&self) -> bool {
    self.is_active
  }

  pub fn set_name(&mut self, name: String) {
    self.name = name
  }

  pub fn set_email(&mut self, email: String) {
    self.email = email
  }

  pub fn set_age(&mut self, age: i32) {
    self.age = age
  }

  pub fn set_active(&mut self, is_active: bool) {
    self.is_active = is_active
  }
}

How do I import this into the src/main.rs file?

use user::entity::User;

fn main() {
  let mut _user = User::new("John".to_string(), "j@j.com".to_string(), 30, true);

  println!("User");
  println!("Name: {}", _user.get_name());
  println!("Email: {}", _user.get_email());
  println!("Age: {}", _user.get_age());
  println!("Active: {}", _user.is_active());

  _user.set_active(false);
  _user.set_name("Jane".to_string());
  _user.set_email("j@j2.com".to_string());
  _user.set_age(43);

}

Do I have to create any more files? Do I have to put something in cargo.toml? I've read the official documentation but I still don't understand.


Solution

  • You need to create a module for each level.

    The good way to do this is to put in main.rs:

    pub mod user;
    

    Then create a file src/user/mod.rs or src/user.rs and put in it:

    pub mod entity;
    

    Then create a file src/user/entity/mod.rs or src/user/entity.rs and put in it:

    pub mod user;
    

    Then change the use declaration at the top of main.rs to:

    use user::entity::user::User;
    

    Then your code should work.

    The quick-and-dirty (and bad) way is to put in main.rs:

    pub mod user {
        pub mod entity {
            pub mod user;
        }
    }
    

    And change the use declaration as above, and you're done.