FAQ - Help and questions

How do I pass arguments to my program with cargo run, and run a second binary or an example?

#cargo#command-line#toolingpublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Put -- after cargo run, and everything after it goes to your program, not to Cargo. Choose another binary with --bin name and an example with --example name. Inside the program, std::env::args yields the arguments, and the first item is the program itself.

Checked with rustc 1.93.0 and cargo 1.93.0, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

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#

  1. Read the arguments in the program. args().skip(1) drops the program's own name.
src/main.rsrust
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()),
    }
}
  1. Run it with and without arguments.
text
> cargo run -q
no arguments
> cargo run -q -- Ada
Hello, Ada!
> cargo run -q -- Ada --shout
HELLO, ADA!
  1. A project can hold more than one program. Files in src/bin/ are extra binaries and files in examples/ are examples. Select them by name:
text
> cargo run -q --bin other
this is the second binary
> cargo run -q --example demo
this is an example

When 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 clap crate handles help text, types and errors.
  • Expecting cargo run to 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.

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet