Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use module from parent directory in rust

Tags:

module

rust

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?

like image 640
willowsplit Avatar asked Mar 03 '23 21:03

willowsplit


1 Answers

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;
like image 190
Alice Ryhl Avatar answered Mar 13 '23 05:03

Alice Ryhl