みんな大好き lazy_static!
ですが、これと command-line parsing を組み合わせるとすごい便利です。
問題点
コマンドライン引数をパースしたいけど、パースした結果をコードの色々な所からアクセスしないといけない。じゃどうするのか?
以下のようにパース結果への参照を渡しまくるという方法もありますが、
fn some_code(args: &Args, /* 他の引数 */) {
...
some_other_code(args, ...);
}
fn some_other_code(args: &Args, /* 他の引数 */) {
...
}
fn main() {
let args: Args = /* パースした結果 */
some_code(&args, ...);
}
あまりよくないでしょう。
そこで lazy_static!
パース結果を lazy_static!
で包んで、初期化する際にコマンドラインをパースするコードを書けば、パース結果の参照を必要とせず、そのまま使うことができます。
lazy_static! {
static ref ARGS: Args = {
Docopt::new(USAGE)
.and_then(|d| d.deserialize())
.unwrap_or_else(|e| {
println!("Failed to parse command-line arguments.");
e.exit();
})
};
}
fn main() {
match ARGS.flag_verbose {
true => be_verbose(),
false => (),
};
}