Import from neighbour folder

I've got following project structure, common, project1 and project2 are folders.
I am defining in cargo.toml two binaries main.rs in project1 and main.rs in project2

common
    common1.rs
    common.rs
    mod.rs
project1
    main.rs
project2
   main.rs

I've defined few pub struct in common.rs and common1.rs but i can't import then in any of main.rs.
How can i accomplish that?

The normal and best way to share code between binaries is to define a library. Create src/lib.rs and put mod common; in it, then use it as use project name::common::common1::Whatever; from main.rs.

I've created lib.rs in top directory with

mod common;

And inside mod.rs in common there is, but it still doesnt work

mod common {
    pub mod client_builder {}
    pub mod parse_url {}
}

EDIT:
I am trying to import it like this use crate::common::common1::SomeStruct

crate:: refers to the current crate, which is your binary. You need to use a path starting with the name of your library, which by default is equal to the [package] name = "..." in your Cargo.toml.

You don't need to declare a module inside its own file; each module only needs one mod. Doing this will result in you needing to use common::common:: to access its contents, because you've declared two nested modules that happen to have the same name. Just declare mod common; in lib.rs, and in common/mod.rs put the contents you want the common module to have.

After i change content of lib.rs to mod common;

When i try to use name of module instead of crate:: it throws use of undeclared crate or module.

Your path must start with the name of the library crate, not the name of any module.

If that doesn't clarify things, please post the full, unedited output of cargo check — there are many details in it which will help us understand exactly where the problem is. Also showing us exactly what files you currently have will help.

Sorry, i've made mistake writing, i've used name of the library defined in Cargo.toml under [package] name=... as you suggested

error[E0433]: failed to resolve: use of undeclared crate or module `project_name`

 --> src/project1/main.rs:8:5
  |
8 | use project_name::common::ClientBuilder;
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^ use of undeclared crate or module `project_name`

This is full error that i was talking about

Ok i've made a type libs.rs instead of lib.rs. But i can't still import the struct.

8 | use project_name::common::ClientBuilder;
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ no `ClientBuilder` in `common`

UPDATE:
I can use the ClientBuilder but when its inside mod.rs file

Solver:
When i change content of mod.rs to

pub mod common {
    pub mod common1;
    pub mod commonl;
}

Everything works

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.