简体   繁体   中英

Passing program arguments through Cargo

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 (eg 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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM