import - 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
解决方案
使用一个库和两个二进制文件,然后在两个二进制文件中重用该库的代码。例子:
货运.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 上发布它,让其他人从中受益。
推荐阅读
- mapbox-gl-js - 在 MapboxGL 上显示的 mvt 矢量图块
- html - 在引导列中定位元素
- python - 通过使用 Python 应用 Excel 公式创建一个新的数据框列
- python - 从跨度中提取文本
- php - 更新到 PHP 7.4 后的错误:未捕获的错误:调用数组上的成员函数 find()
- kubectl - k8s 集群上的“kubectl get”cli 响应时间太长
- javascript - HTTP 响应中缺少 react-admin
- c# - 在 Visual Studio 2019 社区中将 Azure API 链接到 C# ASP.Net 项目的问题
- java - 使用 Jolt 对键进行 JSON 到 JSON 转换
- angular - 为 Angular 项目混合引导程序和谷歌材料