Managing Dependencies of Multiple Binaries

I have a rust project that has multiple independent binaries used for lambda functions. They all rely on shared dependencies as well as different dependencies unique to each binary. How do I structure a Cargo.toml file this way using workspaces? A simple example to show me how this would work for my use case would be very helpful. Thanks!

Use multiple packages in a single workspace. Each package has its own Cargo.toml producing its own bin, and requiring its own dependencies. A shared library can also be referenced by each bin package.

The pixels repo is good example, since it uses exactly the described organization for its own examples. parasyte/pixels: A tiny hardware-accelerated pixel frame buffer. :crab: (github.com)

2 Likes

You can also just have a single package with many binaries. If there's shared code, you can also have a library in the same package.

Then, you'd make any dependencies that aren't needed by all binaries optional, and on each binary use required-features.

If you decide to use the workspace method instead, you can read about it here: Workspaces - The Cargo Book

3 Likes

If I use required-features for each binary, do I need to pass in the features flag when building the rust project using cargo build? I build my rust projects using sam build which builds all of the binaries in the package which doesn't appear to support feature flags...

You could make all features default.

I wouldn't worry about feature flags, tbh. Just build everything you need. If most of your functionality is implemented in a shared library and the binaries are just simple CLI wrappers, it won't make much difference.

Feature flags are primarily useful for when you want to give downstream users the ability to pick just the functionality they need, or if you've got a complicated story around platform-specific code or dependencies. For example, the wasmer crate makes you explicitly pick which compilers you want to enable for compiling WebAssembly to machine code because linking with LLVM is a PITA and Cranelift is big enough that you don't want to compile it if you don't need to.

They're also useful if your project is huge and you want to reduce compile time for specific binaries. But yeah, if you aren't having these problems, just make all the dependencies required. You can change it later.

1 Like