OPTIONS: -V, --version Print version info and exit --list List installed commands --explain <CODE> Run `rustc --explain CODE` -v, --verbose Use verbose output (-vv very verbose/build.rs output) -q, --quiet No output printed to stdout --color <WHEN> Coloring: auto, always, never --frozen Require Cargo.lock and cache are up to date --locked Require Cargo.lock is up to date -Z <FLAG>... Unstable (nightly-only) flags to Cargo, see 'cargo -Z help' for details -h, --help Prints help information
Some common cargo commands are (see all commands with --list): build Compile the current project check Analyze the current project and report errors, but don't build object files clean Remove the target directory doc Build this project's and its dependencies' documentation new Create a new cargo project init Create a new cargo project in an existing directory run Build and execute src/main.rs test Run the tests bench Run the benchmarks update Update dependencies listed in Cargo.lock search Search registry for crates publish Package and upload this project to the registry install Install a Rust binary uninstall Uninstall a Rust binary
See 'cargo help <command>' for more information on a specific command.
一目了然,如此我们就知道如何使用cargo了。
创建项目
让我们开始构建一个新的命令行程序吧!
我在这里将项目命名为meow。
1 2
$ cargo new meow $ cd meow
参数
正如上面看到CLI的样子,CLI应有一些参数。
添加参数最简单的方法是:
1 2 3 4 5 6 7
// main.rs use std::env;
fnmain() { let args: Vec<String> = env::args().collect(); println!("{:?}", args); }
fnmain() { // The YAML file is found relative to the current file, similar to how modules are found let yaml = load_yaml!("cli.yml"); let m = App::from_yaml(yaml).get_matches();
/// Simple program to greet a person #[derive(Parser, Debug)] #[clap(author, version, about, long_about = None)] structArgs { /// Name of the person to greet #[clap(short, long)] name: String,
/// Number of times to greet #[clap(short, long, default_value_t = 1)] count: u8, }
fnmain() { let args = Args::parse();
for _ in0..args.count { println!("Hello {}!", args.name) } }
观察输出:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
$ demo --help clap [..] Simple program to greet a person
USAGE: demo[EXE] [OPTIONS] --name <NAME>
OPTIONS: -c, --count <COUNT> Number of times to greet [default: 1] -h, --help Print help information -n, --name <NAME> Name of the person to greet -V, --version Print version information
let key = "HOME"; match env::var_os(key) { Some(val) => println!("{}: {:?}", key, val), None => println!("{} is not defined in the environment.", key) }