Answer#
cargo run has options of its own (--release, --bin, -p), and so does your program. The lone -- separates them: Cargo reads what is before it and hands the rest on unchanged.
How to do it#
- Read the arguments in the program.
args().skip(1)drops the program's own name.
fn main() {
let args: Vec<String> = std::env::args().skip(1).collect(); // skip(1): the first item is the program itself
match args.as_slice() {
[] => println!("no arguments"),
[name] => println!("Hello, {name}!"),
[name, flag] if flag == "--shout" => println!("HELLO, {}!", name.to_uppercase()),
_ => println!("got {} arguments: {args:?}", args.len()),
}
}- Run it with and without arguments.
> cargo run -q
no arguments
> cargo run -q -- Ada
Hello, Ada!
> cargo run -q -- Ada --shout
HELLO, ADA!- A project can hold more than one program. Files in
src/bin/are extra binaries and files inexamples/are examples. Select them by name:
> cargo run -q --bin other
this is the second binary
> cargo run -q --example demo
this is an exampleWhen a package has several binaries, default-run = "name" under [package] tells cargo run which one to start without a flag.
Common mistakes#
- Forgetting the
--and getting "unexpected argument" from Cargo. - Parsing arguments by hand for anything beyond a flag or two. The
clapcrate handles help text, types and errors. - Expecting
cargo runto pass the arguments through a shell: quotes behave as your shell treats them, not as Cargo does.
In Ruststudio#
Run > Start Without Debugging (cargo run) starts the project; Run > Run Release does the same with a release build.