What's the right way to declare & run "crate-type" examples?

I have a package with an examples directory, which in turn houses a "crate-type" example (as opposed to a file).

.
├── Cargo.toml
├── examples
│   └── my_example
│       ├── Cargo.toml
│       └── src
│           └── main.rs
└── src
    └── lib.rs

Trying to run this with cargo run --example my_example yields an error:

error: no example target named `my_example`

If I move main.rs out of src and up into my_example, Cargo can find it, but it appears to ignore the Cargo.toml.

I know the dev-dependencies from the top-level package will be automatically linked, but if possible, I think I'd rather list them inside the example's Cargo.toml. axum does this, but axum is a workspace and declares every crate inside examples as its own package. I'm not using Cargo Workspaces, so I can't copy that.

For the layout, one way is make a workspace for my_example and use
cargo run -p my_example instead of --example my_example .

# ./Cargo.toml
# rest of original contents like [package] [dependencies] etc
[workspace]
members = ["examples/my_example"]

Links you should read:

You don't have to make all things under examples be members like axum does.
But if you want cargo run --example xxx to run a package under examples, it's impossible due to the way cargo is designed.

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.