CLI project structure in Rust

Hello everyone,
I’d like to start another command-line application, but I’m unsure about the directory structure for this type of project. Many of the applications I’ve created are in a single file – in this case, the main file.
Many thanks if anyone can help me with how to structure my project.

have a look at this. it's a Rust project for a CLI command.

It depends application to application. Do you have an idea of what your CLI application will be doing? Will it be short running to do one task? Will it be long running and handle lots of tasks? Will it have interactive input?

cargo init myproj --bin already creates a typical layout.
You have main.rs in src with fn main in it.

It is usually recommended not to have any logic in main.rs (but only the glue-code that accepts CLI arguments), so create lib.rs and move all business-logic there (and cover it with tests).

At some point you will need to split your lib.rs into several modules (or even crates) but it is a completelly different story: splitting the system into modules is one of the most importaint developer skills)

A small example:

Cargo.toml

[package]
name = "my_proj"
version = "0.1.0"
edition = "2024"

[dependencies]
clap = { version = "4.6.7", features = ["derive"] }

src/lib.rs

use clap::Parser;

#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
pub struct User {
    /// Name of a person
    #[arg(short, long)]
    name: String,

    /// User id
    #[arg(short, long, default_value_t = 1)]
    id: u8,
}
impl User {
   // Business logic
    pub fn create(&self) -> bool {
        println!("Create a user {}", self.name);
        true
    }
}

// Tests for it
mod tests {
    use crate::User;

    #[test]
    fn test_create() {
        assert!(
            User {
                name: "dd".to_string(),
                id: 42
            }
            .create()
        );
    }
}

src/main.rs

use clap::Parser;
use my_proj::User;

// thin "entry point"
fn main() {
    let user = User::parse();
    user.create();
}

As an additional tip for deciding what goes where:

  • main.rs describes what happens when the executable is invoked
  • lib.rs[1] describe how that work is done

  1. and any modules, dedicated library crate, etc. ↩︎

It's a bit subjective, but I generally like to:

  • create one file per core type (closely related helper types can be in the file of the type they help, though).
  • have purely organizational module for grouping similar items together.
  • re-export into the organizational modules if the defining module is only there to help keep things clean.
  • I put each command for my binary in a separate module.

Having lib separate from main is nice organizationally if you think that your binary's logic could be useful for another project to link in. But if you don't want to maintain such a public dependency I could see arguments against that. (EDIT: While this is true, it might be a tad over-cautious. You could instead just advise your users to not depend on the exported library. Up to you!)

You can see an example for a small internal binary I've made here, in my typed-ident project: typed-ident/generator at main · sigseis/typed-ident · GitHub

EDIT: My usage of clap in this example is not very idiomatic, so I recommend digging a bit deeper there. Specifically, I'm not actually creating custom commands. I more mean to share this for project structure.

While this is about libraries mainly, I have written an article on this organization strategy:

Just sharing in case it helps to see some explanation for why I organize this way.

Should we move the logic out of frontend (UI/Web/CLI) modules? The classical answer is "yes, because we might need to reuse it in another frontend" but I think this is not the only reason to do it:

  1. Even if you will never have another frontend, you still have tests, and tests are actually your "fake" frontend.
  2. System with clear boundaries is usually easer to understand.
  3. Some errors (like double-escaping) have less chances to appear (you always escape things on a frontend for example)

I'm not saying it never makes sense, often in fact it does! I'm just adding the nuance that if you export a library and a binary, third-parties could take a dependency on that library (unless maybe I'm misunderstanding what is being suggested), when you really maybe had only meant for it to be purely used to help organize your binary's code.

Unless I'm certain I want to commit to that, I usually start with just a binary, and then I organize my modules in a sensible way within the binary itself. Often opting to keep the actual commands that accomplish what the binary is called for as simple as possible, only using helper types defined elsewhere in the binary, via some common logic module or something.

I guess this accomplishes something akin to simulating an "internal crate", a thing that I still really wish we had in Rust.

EDIT: Though, on second thought, I guess you could just clearly document the crate as "internal only" if you don't want or intend to have anyone but your binary link it in. I see that quite a bit on crates.

I think pub(crate) might help here.

I also wish we had

Ah! I didn't realize you could use pub(crate) across the library and binary, I guess that makes sense, since it's all the same crate! :slight_smile:

Sorry for the bad suggestion then, I will strike it out. In that case, I agree in that separation.

Ah! I didn't realize you could use pub(crate) across the library and binary,

And now I am not sure if it works that way, they can probably be two different crates, I should have checked it before suggesting:)

If a package contains src/main.rs and src/lib.rs, it has two crates: a binary and a library, both with the same name as the package.

So, your point was valid. Sorry.

Ah, yeah - I just tried it and it doesn't work. That's unfortunate...

Still though, I would agree with you that it's more common to have the main/lib crate separation as you suggest, so I'll lighten my suggestion here. I'm basically agreeing with the careful organization, except that I hide it in a separate module in the binary instead of a separate crate.

But, you can also just let your dependents know that the exported lib is only for the binary's internal use. And in that case you can probably structure and test it more predictably like a library, and certainly it would have stronger separation. So a thin main and a supporting library is probably the right general recommendation. :slight_smile:

I'm a bit sensitive to exporting things (perhaps to a needless degree), so my comment might have been a bit over-stated.

I personally haven't used any yet, myself, but might be good to use the cli-battery-pack template (used with cargo bp) to start a new cli project.