[Solved] Passing arguments to cargo run example?

  1. I have the following code:
  cargo run --release --example z_main 
  1. This runs the z_main example fine. Question: how do I pass arguments to the z_main/main.rs::fn main() function ?

Apparently I can just pass it as:

cargo run --release --example z_main foo bar
1 Like

Add -- before your arguments.

1 Like

@kornel: Can you point me to thwere the -- is documented? (It's working for me without the --, but I'm interested in reading up on this.)

$ cargo run --help
cargo-run
Run the main binary of the local package (src/main.rs)

USAGE:
    cargo run [OPTIONS] [--] [args]...

OPTIONS:
        --bin <NAME>...             Name of the bin target to run
       ...

If neither `--bin` nor `--example` are given, then if the package only has one
bin target it will be run. Otherwise `--bin` specifies the bin target to run,
and `--example` specifies the example target to run. At most one of `--bin` or
`--example` can be provided.

All the arguments following the two dashes (`--`) are passed to the binary to
run. If you're passing arguments to both Cargo and the binary, the ones after
`--` go to the binary, the ones before go to Cargo.
1 Like

You're passing bare-word args to the example, which is working, but if you wanted to pass, say --help cargo might grab that as an option to itself. Passing it as -- --help makes it explicitly an argument to the program being invoked. It's a common pattern among tools that invoke other programs.

3 Likes

@OptimisticPeach @dcarosone : Thanks for clarifying --. Makes sense now.