Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rust use sibling module with no main.rs

My project has a client and a server binary. So my Cargo.toml looks something like

[[bin]]
name = "server"
path = "src/server/mod.rs"

[[bin]]
name = "client"
path = "src/client.rs"

My file structure looks something like:

.
├── client.rs
├── server
│   ├── something.rs
│   └── mod.rs
└── shared
    ├── mod.rs
    └── something2.rs

What I want to do is use anything from shared in server/mod.rs. To do that I tried to have a mod shared and use crate::shared in the server/mod.rs but I got the error "no ‘shared’ in the root" (It is only looking in shared/). I don’t have a main.rs where I could properly declare the modules.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So another thing I tried was using server.rs instead of server/mod.rs. This worked partially, as I now can declare mod shared. However, I cannot access anything in server/something.rs anymore. Is there any way to get the server.rs see the contents of server/ or is there a way to make server/mod.rs see the contents of a neighboring module without having a top level main.rs?

>Solution :

You can use the #[path] attribute:

#[path = "../shared/mod.rs"]
mod shared;

But the proper way is to have a library, in addition to client and server, and make both depend on it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading