Search code examples
rustrust-crates

Publicly using the public api of a third party crate?


I'd like to publicly use the public API of a third party crate while implementing a new crate.

For example, suppose I'm implementing a crate my_serializer which needs some kind of u7 type. This doesn't exist in the core language, or standard library but there's a nice implementation in the external crate ux. It would be very convenient to do the following:

// my_serializer/lib.rs
extern crate ux;
pub type U7 = ux::u7;

But this forces clients of my_serializer to also be clients of ux. Is that a reasonable thing for a crate developer to do? or is it considered bad practice?

The alternative would be to wrap this ux::u7 type inside my_serializer, but then I'd need to reimplement all of the Trait implementations, of which there are hundreds! There isn't an easy way to macro-derive these for wrapped types, right?


Solution

  • But this forces clients of my_serializer to also be clients of ux. Is that a reasonable thing for a crate developer to do? or is it considered bad practice?

    There is generally no problem with this. It is possible and fairly common for a library crate to expose public APIs from another dependency. Only two main concerns when doing this:

    • Ensure that a sufficient portion of the public dependency's API has been exposed in your own crate. An insufficient coverage may lead to inconveniences, especially if the same crate is imported with different versions and you depend on traits from the transitive dependency.

      // expose the whole crate
      pub extern crate ux;
      

      In this case, it should be safe to expose a single type instead, considering that ux does not declare any traits at the time of writing.

      // Or only expose this struct
      pub use ux::u7;
      
    • Bear in mind that any breaking change to the dependency crate's API also constitutes a breaking change in your own crate. If this is undesirable, then that would call for an additional abstraction layer.

    See also: