What is the best way to implement optional library dependencies in Rust?

811 views Asked by At

I am writing a toy software library in Rust that needs to be able to load images of almost any type into an internal data structure for the image. It is early days for the Rust ecosystem, and there is no one library/set of bindings that I would trust for this task.

I would ideally like:

  • Support multiple redundant external libraries that may or may not be available at runtime
  • Support multiple redundant external libraries that may or may not be available at compile-time.
  • Include at least one fallback implementation that ships with my code.
  • Fully encapsulate all of the file loading stuff behind a function that does path -> InternalImage loading.

Is there a best practice way to implement optional dependencies like this in Rust? Some of the libraries will be Rust, and some of them will probably be C libraries with Rust bindings.

1

There are 1 answers

0
barjak On

Cargo, the Rust package manager, can help with that. It lets you declare optional compile-time dependencies. See the [features] section of Cargo's documentation.

For runtime dependencies I'm not sure. I think std::dynamic_lib could be helpful. See an example of using DynamicLibrary in a previous SO question.