Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
791 views
in Technique[技术] by (71.8m points)

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

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; 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

Please log in or register to answer this question.

1 Answer

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share
...