Run different files under the same folder


#1

There is a folder with several files under it, let’s say, first.rs, second.rs… , and each of them contains a ‘main’ function.
I know 'rustc filename.rs ’ works fine for simple files to build.
But what would the cargo version be, for making them built and run?
Thanks!


#2

If you put them all under src/bin/ (relative to your Cargo.toml) then they will all be built by cargo build. But when there are multiple binaries, you have to specify which to run, like cargo run --bin first.


#3

Thanks, it works. But is there any official docs available explaining the rules? I found a Github folder named differently from ‘src/bin’:


#4

Yes, you can have examples too. The layout is first described here:
https://doc.rust-lang.org/cargo/guide/project-layout.html

And in more detail here:
https://doc.rust-lang.org/cargo/reference/manifest.html#the-project-layout


#5

It is fine if ‘examples’ put under the project folder, but not ok if put under a sub folder. And the project layout is as below:

project_folder
—sub_folder
------examples
---------first.rs
---------second.rs
---------third.rs
------Cargo.toml (specifying package name as “sub_folder”)

Cargo.toml (specifying package name as “project_folder”)


#6

Ah, I suspect that sub_folder will need something to act as its crate, a src/lib.rs or src/main.rs. Otherwise, why have a nested Cargo.toml at all?

If it’s just about defining your own project layout, note that you can also define explicit paths to examples. In the top level Cargo.toml, you could write:

[[examples]]
name = "first"
path = "subfolder/examples/first.rs"

[[examples]]
name = "second"
path = "subfolder/examples/second.rs"

It’s more tedious, but that’s why the standard layout exists, to make this automatic.


#7

I used your method, and ‘cargo run’ under the top level folder. Didn’t work.
But why the Github folder mentioned above could work?


#8

Can you clarify what didn’t work? What was the full command you ran, and what was the error?

Maybe we should also step back and clarify what you’re really trying to do.


#9

I checked again, and changed [[examples]] to [[example]], then it worked. Thanks for your help. The above-mentioned Github folder works fine without any settings like [[example]], due to that it used [workspace] I guess.