How to use mod from parent folder?

I create two binary file in one package, my file tree as follow:

my_test --
         | -- cargo.toml
         | -- main.rs
         | -- toolkit.rs
         | -- bin
               | -- test_1.rs

and content in cargo.toml:

[package]
name = "my_test"
version = "0.1.0"
edition = "2018"
default-run = "my_test"

[dependencies]

[[bin]]
name = "test_1"

In this case, when I am in mod test_1.rs, how can I import some function from mod toolkit which is in parent folder of test_1.rs?
Thanks.

Is


[dependencies]
foo = { path = "/abs/path/to/foo" }

what you are looking for?

One binary cannot access the contents of another binary. You must use a lib.rs file to have code that is shared between binaries. To do this:

  • Files that should be accessible by every binary should be accessible from the lib.rs file by following mod declarations.
  • Each file should never be mentioned by a mod statement more than once. Any other access should use a use statement.
  • To access things in the library from inside the library, use crate:: to start the path.
  • To access things in the library from inside the binary, use my_test:: to start the path.
2 Likes

Thank for your reply. I just amended my question more clearly, pls check again,thanks.

Thanks for reply.
I change toolkit.rs into lib.rs, but I still donot know how I can refer funtion in a mod of its parent folder.
when I in mod test_1.rs, how can I import function from toolkit.rs or lib.rs in parent folder of test_1.rs, pls tell me more detail about that, thanks.
I originally thought that same source file can be linked in two different binary if I could tell compiler which source files should be linked.

src/lib.rs

pub mod toolkit;

pub fn in_lib_rs() {}

src/toolkit.rs

pub fn in_toolkit() {}

src/bin/test_1.rs

use my_test::in_lib_rs;
use my_test::toolkit::in_toolkit;

fn main() {
    in_lib_rs();
    in_toolkit();
}

src/main.rs

use my_test::in_lib_rs;

fn main() {
    in_lib_rs();
    my_test::toolkit::in_toolkit();
}

yes, It is works! Thank you very much !

I add an example in my package, can I access same function from example.rs?
updated files tree as follow,

my_test --
        | -- example
        |      |-- ex_1.rs
        | -- src
        |      |-- main.rs
        |      |-- toolkit.rs
        |      |-- lib.rs
        |      |-- bin
        |           | -- test_1.rs
        |-- cargo.toml

and content in cargo.toml

[package]
name = "my_test"
version = "0.1.0"
edition = "2018"
default-run = "my_test"

[dependencies]

[[bin]]
name = "test_1"

[[example]]
name = "ex_1.rs"

so when I in ex_1.rs, can I import function in my_test/src/toolkit.rs?
thanks :slight_smile:

If you rename the example dir to examples, you can run cargo run --example ex_1.rs without declaring it in Cargo.toml. It will have your main lib as dependency you can use.

Yes ,it really can be used. Thank you very much!