7

Is it possible to change the name of main.rs and still have commands like cargo run work?

If it is possible could someone give me an example of how to have cargo run target say example.rs?

Brian61354270
  • 8,690
  • 4
  • 21
  • 43
John164
  • 119
  • 1
  • 8

1 Answers1

15

Yes. There are two ways to create executable targets that don't have main.rs at their root.

Method 1: Declare a binary target in cargo.toml

Add an entry to you cargo.toml that resembles the following:

[[bin]]
name = "example"
path = "src/example.rs"

You'll then be able to run your example target via

$ cargo run --bin example

Any number of binary targets can be declared in this way.

Method 2: The bin directory

All Rust files in the src/bin directory of your project act as binary targets. If you move src/example.rs to src/bin/example.rs, you'll be able to immediately run your example binary with

$ cargo run --bin example

No cargo.toml configuration required.

Do note that once you've declare more than one binary target, you will need to use the --bin flag whenever you invoke cargo run. For more information, see the Cargo Targets docs for binary targets.

Brian61354270
  • 8,690
  • 4
  • 21
  • 43