Run examples in subfolders using cargo


#1

Hi,

I have around forty examples in my crate. I want to divide them into four to five folders. Is there a way to run them using cargo, with out putting them in toml file. like

cargo run --example physics/rigid


#2

It’s barely documented, but https://github.com/rust-lang/cargo/pull/4496

You can make

examples/rigid/main.rs

examples/whatever/main.rs

etc.

If you want to, say, put five examples in examples/rigid, then you’ll need to modify Cargo.toml; there’s no convention around this specifically.


#3

Thanks for the reply. I haven’t got it, I will put my problem clearly.

Say I have files like this

dinesh@Personal  dem-rs/examples $  
|  Mac => ls
bouncing_ball.rs	visual_example.rs	hopper.rs     normal_impact.rs
sample1.rs          contact.rs         rigid_1.rs     rigid_2.rs 
rigid_3.rs          rigid_4.rs

To run the examples I can do

dinesh@Personal  dem-rs/examples $  
|  Mac => cargo run --example rigid_4

If I reorganise and put them into folders, i.e.,

dinesh@Personal  dem-rs/examples $  
|  Mac => ls
rigid     sample    bouncing

Can I run it by

dinesh@Personal  dem-rs/examples $  
|  Mac => cargo run --example rigid/rigid_1

From the answer I understood that it is not possible. Is that right?


#4

You can manually specify examples in your Cargo.toml, unfortunately they need to be valid Rust identifiers so you can’t get the namespacing, but it should be possible to have something like

[[example]]
name = "rigid_1"
path = "examples/rigid/rigid_1.rs"

[[example]]
name = "rigid_2"
path = "examples/rigid/rigid_2.rs"

etc...

and run that with

cargo run --example rigid_1