首页 > 解决方案 > 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:

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

标签: importrustrust-cargorust-crates

解决方案


使用一个库和两个二进制文件,然后在两个二进制文件中重用该库的代码。例子:

货运.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"

然后use utils::{...}。该路径取自您的问题,但是将 main 放入 bin/ 并将 utils.rs 重命名为 lib.rs 可能是一种更标准的方法。

如果这个库足够通用,你甚至可以在 crates.io 上发布它,让其他人从中受益。


推荐阅读