Cargo example only dependencies


I am wondering if there is a way to define dependencies only used for examples in the /example folder. I know that there is [dev-dependencies] witch is for test/bench only (and build script?) dependencies I also know that the examples build when running cargo test. So is it safe to use [dev-dependencies] for example only dependencies?

When using [dev-dependencies] for a more complex scenario, a problem appeared witch did not occur when moving the example to it’s own repo.
So using [dev-dependencies] might not be the best option some scenarios (some feature based variation might still work).

The Problem occurred in a scenario where the crate exposes some traits and the example used implementations for the traits provided by a different crate. The compiler was no longer able to determine that the implementing struct from the other create implemented the interface provided by this crate (through it did, but then it was kind of a circular dependency). After moving the example to it’s own repo, importing all dependencies “normal” the problem was solved (without changing any source code).


Yeah [dev-dependencies] should do the trick! They’re built for all of tests, benchmarks, and examples (and these targets also have access to [dependencies]

For build scripts those use [build-dependencies] and nothing else.


Is it not possible to restrict dependencies to a specific example then? That would be helpful, if not truly necessary.


This came up recently as an issue on the cargo script repo; someone wanted to have dependencies that were specific to a given example, without having to require that dependency for all tests and examples.

One possibility would be to have cargo build learn to use cargo script's embedded manifest format as an additional dependency source just for examples. But then, that kinda kills the whole “one place to look” for this information.


Surely a better approach, if Cargo needs to be modified, is to add a section to Cargo.toml? The only backward incompatibility would be that the few projects using the new feature would not compile with old versions of Cargo, but that’s hardly avoidable in any case.

The argument against adding this feature (in any form) is simply that it wouldn’t be widely used and adds complexity (also the necessity of a new switch to disable examples where the dependencies are troublesome).