如何使用另一个板条箱中的板条箱而不在我的项目中明确定义新的依赖项? [英] How do I use a crate from another crate without explicitly defining a new dependency in my project?

查看:48
本文介绍了如何使用另一个板条箱中的板条箱而不在我的项目中明确定义新的依赖项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 dijkstra 来自 pathfinding crate 的函数:

I want to use the dijkstra function from the pathfinding crate:

pub fn dijkstra<N, C, FN, IN, FS>(
    start: &N, 
    neighbours: FN, 
    success: FS
) -> Option<(Vec<N>, C)> 
where
    N: Eq + Hash + Clone,
    C: Zero + Ord + Copy,
    FN: Fn(&N) -> IN,
    IN: IntoIterator<Item = (N, C)>,
    FS: Fn(&N) -> bool, 

要使用它,我需要实现 num_traits 箱子.但是我怎样才能导入Zero?一个显而易见的方法是将 extern crate num_traits; 添加到我的 crate 中并适当地修复我的 Cargo.toml.但是这样做的时候,不得不看一个依赖的依赖,这样不好.

To use it I need to implement the Zero trait from the num_traits crate. But how can I import Zero? An obvious way is to add extern crate num_traits; into my crate and fix my Cargo.toml appropriately. But in doing so, I have to watch a dependency of a dependency, which is not good.

我可以在不显式依赖 num_traits crate,如下图?

Can I somehow implement Zero without explicit dependency on the num_traits crate, like below?

use pathfinding::num_traits::Zero; 

推荐答案

鉴于将未公开的依赖项从 crate(例如 pathfinding)导入依赖项目的原始意图,即当前不允许.如果依赖项没有被 crate 重新导出,那么它更像是一个实现细节,而不是 API 的一部分.因此,允许依赖访问任何子依赖"将是灾难性的.

Given the original intent of importing non-exposed dependencies from a crate (such as pathfinding) into a dependent project, that is currently not allowed. If a dependency is not re-exported by the crate, that makes it more of an implementation detail than part of the API. Allowing a dependent to access any "sub-dependency" would therefore be catastrophic.

然而,在这种情况下,由于 num_traits 在 crate 的公共 API 中明显使用,因此依赖者可以访问它也是有意义的.实际上,您应该在自己的项目中添加依赖项,同时注意保持兼容版本.否则,cargo 可能最终会构建重复的依赖项.

In this case however, since num_traits is clearly used in the crate's public API, it also makes sense for the dependent to have access to it. As it is, you are expected to add the dependency in your own project, while taking care to keep a compatible version. Otherwise, cargo might end up building duplicate dependencies.

[dependencies]
num_traits = "0.1"

为了避免这种情况,pathfinding 将受益于导出自己的 num_traits,如下所示.PR #6 就是为此目的而创建的,并已合并到 0.1.12 版(谢谢,@SamuelTardieu).

In order to avoid this, pathfinding would benefit from exporting its own num_traits, as below. PR #6 was created for this purpose, and has been merged into version 0.1.12 (thanks, @SamuelTardieu).

pub extern crate num_traits;

完成后,您现在可以完全按照问题末尾的内容进行操作:

With that done, you can now do exactly as written at the end of your question:

use pathfinding::num_traits::Zero;

这篇关于如何使用另一个板条箱中的板条箱而不在我的项目中明确定义新的依赖项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆