14

Is it possible to structure a rust project in this way?

Directory structure:

src
├── a
│   └── bin1.rs
├── b
│   ├── bin2.rs
└── common
    ├── mod.rs

from Cargo.toml:

[[bin]]
name = "bin1"
path = "src/a/bin1.rs"

[[bin]]
name = "bin2"
path = "src/b/bin2.rs"

I would like to be able to use the common module in bin1.rs and bin2.rs. It's possible by adding the path attribute before the import:

#[path="../common/mod.rs"]
mod code;

Is there a way for bin1.rs and bin2.rs to use common without having to hardcode the path?

1 Answer 1

16

The recommended method to share code between binaries is to have a src/lib.rs file. Both binaries automatically have access to anything accessible through this lib.rs file as a separate crate.

Then you would simply define a mod common; in the src/lib.rs file. If your crate is called my_crate, your binaries would be able to use it with

use my_crate::common::Foo;
Sign up to request clarification or add additional context in comments.

4 Comments

This helped me enormously. I have also seen something like use crate:: ... which I thought might refer to "whatever the root crate is" but that returns a compiler error "no X in the root" (where X is my module name). What is the "root" crate, then?
You should think of lib.rs and main.rs as the roots of two entirely distinct crates. When accessing something inside the same crate, you use use crate::, and when accessing something in lib.rs from main.rs, you use use my_crate::. There is no way to access something from main.rs in the lib.rs crate.
Where is the 'my_crate' name determined? The name in cargo.toml?
Yes, it's taken from your Cargo.toml.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.