rust

Is there a cleaner way to organize Rust lib with file per command?


I'm trying to organize a Rust package for a CLI with bunch of commands. Ideally, I'd like to put one command per file. In my mind, it'd look something like this:

├── src
│   ├── commands
│   │   └── echo.rs
│   ├── commands.rs
│   ├── lib.rs
│   └── main.rs

And then, you'd invoke it like mycli::commands::echo(str, std::io::stdout());. However, this is what I had to do to achieve that:

main.rs:

mycli::commands::echo(str, std::io::stdout());

lib.rs:

pub mod commands;

commands.rs

pub mod echo;

pub fn echo(str: &str, mut writer: impl std::io::Write) {
    echo::execute(str, writer);
}

echo.rs:

pub fn execute(str: &str, mut writer: impl std::io::Write) {
    writeln!(writer, "{}", str);
}

Is there a way to get the file structure I want and avoid needing to invoke echo from the commands module?

From what I can tell, Rust wants me to put all of the code in commands.rs to get reference that I want. Or, I need to invoke mycli::commands::echo::execute(str, std::io::stdout()); directly from main.rs.


Solution

  • You can re-export the function from commands with the new name:

    // commands.rs
    mod echo;
    
    pub use echo::execute as echo;