My project structure looks like this:
.
├── Cargo.lock
├── Cargo.toml
└── src
├── bin
│ └── other.rs
├── main.rs
└── util.rs
(code: https://gitlab.com/msrd0/cargo-bin-import)
In my other.rs, I'm trying to reuse code from the util mod, which is declared as a public mod in my main.rs file. I tried the following:
use util::do_sthuse crate::util::do_sthuse cargo_bin_import::util::do_sth (with and without extern crate)mod util; use util::do_sthextern crate util; use util::do_sth (suggested by rustc)None of the above worked and gave me error messages similar to this one:
error[E0432]: unresolved import `crate::util`
--> src/bin/other.rs:1:12
|
1 | use crate::util::do_sth;
| ^^^^ maybe a missing `extern crate util;`?
error: aborting due to previous error
Use a library and two binaries, then reuse the lib's code in the two binaries. Example:
Cargo.toml
[lib]
name = "utils"
path = "src/utils.rs"
# cargo build --bin other
[[bin]]
name = "other"
path = "src/bin/other.rs"
# cargo build --bin main
[[bin]]
name = "main"
path = "src/main.rs"
Then use utils::{...}. The path are taken from your question, but putting main inside bin/ and renaming utils.rs to lib.rs could be a more standard way to do it.
If the library is generic enough, you could even release it on crates.io for others to benefit from it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With