Passing program arguments through Cargo

2019-06-23 02:35发布

问题:

I have some sample code that is currently making use of getopts which is specified as a dependency in Cargo.toml

[dependencies]
getopts = "0.2"

However I can not seem to pass argument (-t, --test) through Cargo (e.g. cargo run --test) for obvious reasons.

Since I have specified that external dependency, trying to run rustc src/main.rs --test won't work either:

src/main.rs:2:5: 2:21 error: unresolved import `getopts::Options`. There is no `Options` in `getopts`
src/main.rs:2 use getopts::Options;
              ^~~~~~~~~~~~~~~~
error: aborting due to previous error

Is there another way to achieve this or some common alternative for the time being?

回答1:

You can pass trailing arguments to cargo run using --:

cargo run -- --test

From the man page:

All of the trailing arguments 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.



回答2:

It looks to me like you had two different problems. First is, how to pass flags to your executable (this was solved by @TartanLlama), the second is your compile error.

For future reference (this is at least true for my system with rust 1.19, cargo 0.20): You used an external crate getopts, which rustc by default does not know. cargo on the other hand understands that. By running cargo rustc (or even better cargo build) instead of rustc the compile error will vanish.



标签: rust