Correct place for private module to be used by multiple executables

Viewed 193

Two executables' sources, foo.rs and bar.rs, are located in src/bin.

Private common functionality exists in src/bin/common.rs.

foo.rs and bar.rs include this functionality with:

mod common;
use common::{Bish, Bash, Bosh};

This works, but src/bin/common.rs doesn't feel like the right path for something which isn't going to be built into an executable.

Moving common.rs to src or src/lib stops foo.rs and bar.rs from seeing it.

Where should I put common.rs and how do I then import it?

2 Answers

A common approach to store shared parts at lib.rs and use these in binaries. Its usage, though, is a bit different than simply mod + use. In fact, library is a separate crate, so you need to access it via crate name (defined in Cargo.toml).

Cargo.toml:

[package]
name = "crate-name"
# ... the rest

src/bin/foo.rs:

fn main() {
  crate_name::fun();
}

src/lib.rs:

pub fn fun() {}
Related