3

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?

fadedbee
  • 42,671
  • 44
  • 178
  • 308

2 Answers2

3

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() {}
Kitsu
  • 3,166
  • 14
  • 28
  • Thanks, this works, but it sends the Rust Language Server a little crazy. The code compiles, but RLS complains: `unresolved import 'crate-name' use of undeclared type or module 'crate-name' rustc (E0432) foo.rs(10, 5): use of undeclared type or module 'crate-name'` – fadedbee Jul 07 '20 at 05:58
  • RLS quite a strange beast. I think [rust-analyzer](https://github.com/rust-analyzer/rust-analyzer) is much better choice know, try it out. – Kitsu Jul 07 '20 at 06:12
  • Many thanks. Rebooting fixed the RLS issue. VSCode extension warns that rust-analyzer is incomplete. – fadedbee Jul 07 '20 at 12:05
1
example
├── Cargo.toml
└── src
    ├── bin
    │   ├── bar.rs
    │   └── foo.rs
    ├── common.rs
    └── lib.rs

foo.rs and bar.rs:

#[path = "../common.rs"]
mod common;
use common::{Bish, Bash, Bosh};

also see: How can I use a module from outside the src folder in a binary project, such as for integration tests or benchmarks?

ghtz
  • 41
  • 2
  • Can you explain what the `#[path = "../common.rs"]` means? I've never seen that. Does it only apply to the next statement or do you need to be careful with other imports? Would be great if you could explain your answer a bit more. – Cornelius Roemer May 22 '22 at 21:34
  • The link you provided actually recommends strongly against using the solution you suggest here. – Cornelius Roemer May 22 '22 at 21:39
  • [Module Source Filenames](https://doc.rust-lang.org/reference/items/modules.html#module-source-filenames) – ghtz May 23 '22 at 06:34
  • This is appropriate when the specified module does not depend on other project files. – ghtz May 23 '22 at 06:36