如何使用本地未发布的crate?

224
我做了一个库:
cargo new my_lib

我想在另一个程序中使用那个库:

cargo new my_program --bin

extern crate my_lib;

fn main {
    println!("Hello, World!");
}

我需要做什么才能让这个工作?

它们不在同一个项目文件夹中。

.
├── my_lib
└── my_program

希望这样讲起来清楚明白。

我原以为能按照Cargo指南覆盖路径,但它说:

您不能使用此功能告诉Cargo如何找到本地未发布的包。

这是在使用最新稳定版本的Rust(1.3)时发生的。

2个回答

300

在你的可执行文件的 Cargo.toml 中添加依赖项部分,并指定路径:

[dependencies.my_lib]
path = "../my_lib"

或等效的替代 TOML 格式:

[dependencies]
my_lib = { path = "../my_lib" }

查看Cargo文档以获取更多详细信息,如如何使用Git存储库而不是本地路径。


14
有没有一种方法可以在开发时自己使用本地 crate,同时让 Cargo.toml 引用 crates.io,以便其他人也可以构建我的代码? - David Roundy
1
目前默认情况下无法实现。但是您可以在本地分支上工作,将Cargo.toml替换为本地依赖项引用(或混合引用),并在合并之前或期间还原或保留主要的Cargo.toml文件。 - Paul-Sebastian Manole
16
如果你仍在寻找答案,现在已经可以实现你所要求的功能。你可以为一个依赖项同时指定“version”和“path”,当你发布它时,它会将“path”部分删除 :) - Connie Hilarides
详细文档可在 https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html#specifying-path-dependencies 上找到。 - David J.
7
可以使用git而不是version来实现相同的效果吗?例如 my_lib = { path = "...", git = "..." } 这样我就可以在开发过程中使用本地副本,在有人克隆存储库并尝试编译程序时使用远程git。 - Ruben Kostandyan
除了使用相对路径之外,应该有更好的方法来完成这个任务,因为相对路径可能会发生变化。如果一个木箱依赖于另一个木箱,并且两者都在同一个工作区中,是否有办法指定依赖关系而不使用相对路径? - FreelanceConsultant

0

我正在寻找与mvn install等效的命令。虽然这个问题并不完全是我的原始问题的重复,但任何偶然发现我的原始问题并跟随链接到这里的人都会找到更完整的答案。

答案是“没有与mvn install等效的命令,因为您必须在Cargo.toml文件中硬编码路径,这可能在其他人的计算机上出错,但您可以接近实现目标。”

现有的答案有点简略,我不得不花费更长的时间才能使事情真正起作用,所以这里提供更多细节:

/usr/bin/cargo run --color=always --package re5 --bin re5
   Compiling re5 v0.1.0 (file:///home/thoth/art/2019/radial-embroidery/re5)
error[E0432]: unresolved import `embroidery_stitcher`
 --> re5/src/main.rs:5:5
  |
5 | use embroidery_stitcher;
  |     ^^^^^^^^^^^^^^^^^^^ no `embroidery_stitcher` in the root

rustc --explain E0432 包含了这段话,重复了Shepmaster的回答:

Or, if you tried to use a module from an external crate, you may have missed the extern crate declaration (which is usually placed in the crate root):

extern crate core; // Required to use the `core` crate

use core::any;

use切换到extern crate给了我以下结果:

/usr/bin/cargo run --color=always --package re5 --bin re5
   Compiling embroidery_stitcher v0.1.0 (file:///home/thoth/art/2019/radial-embroidery/embroidery_stitcher)
warning: function is never used: `svg_header`
 --> embroidery_stitcher/src/lib.rs:2:1
  |
2 | fn svg_header(w: i32, h: i32) -> String
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: #[warn(dead_code)] on by default

   Compiling re5 v0.1.0 (file:///home/thoth/art/2019/radial-embroidery/re5)
error[E0603]: function `svg_header` is private
 --> re5/src/main.rs:8:19
  |
8 |     let mut svg = embroidery_stitcher::svg_header(100,100);
  |                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

我不得不在那个函数前面加上一个pub

pub fn svg_header(w: i32, h: i32) -> String

现在它能够正常工作了。


3
现在这个答案是一篇迷你文章:http://www.purplefrog.com/~thoth/rust-external-libraries/ - Mutant Bob
1
此外,extern crate 只能在 2015 版本或其他情况下使用,因为 cargo 自身已经链接了这些 crates。 - Rafaelplayerxd YT

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接