LoginSignup
3
2

More than 5 years have passed since last update.

lazy_static! と docopt の組み合わせは最高

Posted at

みんな大好き 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 => (),
    };
}
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2