Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reuse code from the main bin in another bin?

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_sth
  • use crate::util::do_sth
  • use cargo_bin_import::util::do_sth (with and without extern crate)
  • mod util; use util::do_sth
  • extern 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
like image 840
msrd0 Avatar asked Oct 29 '25 22:10

msrd0


1 Answers

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.

like image 141
AdminXVII Avatar answered Nov 01 '25 12:11

AdminXVII



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!