【问题标题】:How to use a local unpublished crate?如何使用本地未发布的 crate?
【发布时间】:2021-11-30 01:58:02
【问题描述】:

我已经创建了一个库:

cargo new my_lib

我想在不同的程序中使用该库:

cargo new my_program --bin
extern crate my_lib;

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

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

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

.
├── my_lib
└── my_program

希望这是有道理的。

我以为我可以按照Cargo guide 覆盖路径,但它指出

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

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

【问题讨论】:

    标签: rust rust-crates


    【解决方案1】:

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

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

    或等效的替代 TOML:

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

    查看Cargo docs for specifying dependencies 了解更多详细信息,例如如何使用 git 存储库而不是本地路径。

    【讨论】:

    • 有没有办法自己使用本地 crate(用于开发),同时让 Cargo.toml 引用 crates.io,以便其他人也可以构建我的代码?
    • 目前默认不可能。但是,您可以在本地分支上工作,将 Cargo.toml 替换为本地依赖引用(或混合引用),然后在合并之前或合并期间,恢复或保留主 Cargo.toml 文件。
    • @DavidRoundy 如果您仍在寻找答案,现在可以按照您的要求进行操作。您可以为依赖项同时指定version 和path,当您发布它时,它将删除path 部分:)
    • 详细文档可在doc.rust-lang.org/cargo/reference/…获取
    • 是否可以使用git 而不是version 做同样的事情?像 my_lib = { path = "...", git = "..." } 这样的东西,这样我就可以在开发过程中使用我的本地副本,当有人克隆 repo 并尝试编译程序时使用远程 git?
    【解决方案2】:

    我正在寻找与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 的回答相呼应的段落:

    或者,如果您尝试使用外部 crate 中的模块,您可能错过了 extern crate 声明(通常放在 crate 根目录中):

    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
    

    现在可以了。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-13
    • 2017-10-18
    • 1970-01-01
    • 2012-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多