Search code examples
rustrust-diesel

Move Diesel methods into other directories


I'm following the Diesel examples guide, and my project looks exactly like this. I want to change it so that instead of running cargo run --bin publish_post 1, you use cargo run and are presented with a loop prompting you for what action you want to run.

I've moved everything out of bin/ and into the controllers/ directory. I want to reference this in main.rs as use controllers::post, so I have access to post::delete(), etc.

Once I move the files out of bin/, all the imports break. Likewise, I can't reference it from lib.rs.

Why do none of my imports work when the files are moved? How I could access the methods from these files?

I want a structure like this:

├── controllers
│   └── posts.rs
├── lib.rs
├── main.rs
├── models.rs
├── schema.rs

And within main.rs, I want to be able to do something like:

use controllers::posts;

pub fn main() {
    // pseudocode
    loop {
        println!("what action would you like to perform?");
        let ans = capture_input();

        if ans == "insert" {
            posts::insert();
        } else if ans == "delete" {
            posts::delete();
        }
    }
}

Solution

  • Making a folder doesn't automatically make a Rust submodule. You need to do two things:

    1. Declare the module explicitly in the crate root (lib.rs or main.rs):

      mod controllers;
      
    2. Create controllers/mod.rs file and declare a submodule in it:

      mod posts;