2

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
4

1 回答 1

2

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

货运.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 上发布它,让其他人从中受益。

于 2019-08-11T21:49:48.413 回答