How to import a struct from a crate without importing unused dependencies?

Consider this setup:

// crate A

struct Example { field1: u8, field2: u8 }

impl Example {
  fn use_lib() { ... }
}

// crate B

use crateA::Example;

Crate B uses a struct from crate A that has an associated function that uses a few crate A dependencies. These crate A dependencies that needed in crate B (only the struct is needed). Is there a way import the struct from crate A in crate B without importing all the dependencies of crate A?

Solutions I'm considering:

  • Move struct into crate C, create a wrapper in crate A and implement the functions on the wrapper
  • Create a macro that copies the struct (without the associated functions) from crate A into crate B. A bit harder if the struct depends on other structs defined in crate A.

Curious to hear other Ideas or thoughts

Even if the use_lib function is available as an import, that doesn't mean it will be included in the final executable. You don't need to "not import it", simply don't call it and it will be ignored by the compiler/linker.

Thanks for the reply. In my case the concern is not just executable size, it's also compile speed and the build target (crate B sometimes is built for wasm32-unknown-unknown and many dependencies in crate A do not build for that target).

You don't really have much control about how other people's code gets compiled, other than forking or using cargo patching

But ideally, if you have a dependency chain app -> lib -> other, and other isn't necessary to use lib, then it would have a cargo feature that all functionality requiring other is configured to require, including the dependency itself. Often this feature is simply the dependency itself being declared optional, and the caller automatically gets it enabled if they also add this dependency themselves.

There's quite a bit of design and care needed for adding crate features, though, be careful to ensure that not building the dependency actually does make a practical difference, for example with cargo build --timings

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.