How do I use a crate from another crate without explicitly defining a new dependency in my project?

匿名 (未验证) 提交于 2019-12-03 08:39:56

问题:

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, 

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.

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

use pathfinding::num_traits::Zero; 

回答1:

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.

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"

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;


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!