Search code examples
rust-cargo

Building/running Cargo based examples


For certain examples, I want to build/run them using Cargo. My examples directory looks as follows:

  • examples/
    • test1.rs
    • test2/
      • Cargo.toml
      • src/
        • main.rs
        • ...

Is this possible? If it is, what are my options to accomplish this?

I tried a few things already, but they either don't work (e.g. using a workspace for the examples and adding that as member to the project workspace) or don't have the desired effect (e.g. adding the example crates as members to the project workspace).

Currently I'm building them using a shell script, but integrating then would be prefered. I'm thinking of adding the example crates as [[example]] to one of the actual crates, but I can't find out how. Also, there might be an easier/prefered way I'm overlooking...


Solution

  • Your directory structure looks like it should work.

    You should be able to run test1.rs like so: > cargo run --example test1, for example, assuming it has a pub fn main(). See the cargo book, run command, examples for details on passing in command line arguments to your example.

    But I'm not sure that's your question! If you'd provide some specific commands you've tried and the (unexpected, or unclear) errors you got, you'll probably get more specific answers.

    Cargo doesn't have great tooling for generating examples, e.g, doesn't have a command to create the folder structure and a sample main.rs. I found this enhancement request from 2020, and it still seems relevant today: https://github.com/rust-lang/cargo/issues/6939. If that's the gist of your question (automated generation), you might weigh in on that thread.