🐱

『実践Rustプログラミング入門』で学ぶ

2024/04/21に公開

『実践Rustプログラミング入門』を読んでいく
https://www.shuwasystem.co.jp/book/9784798061702.html

コードの公開場所

コードはこちらで公開されている
https://github.com/forcia/rustbook

4章でコマンド入力アプリを学ぶ

標準クレートだけのパターン

use std::env;

fn main() {
    let args: Vec<String> = env::args().collect();
    println!("{:?}", args);
}
  • std::env::args()でコマンドプロンプトからの入力を拾う
  • .collect()でベクター形式にする
  • コマンドプロンプトからの入力をargsに入れる
  • 型はVec<String>とする(文字列のベクター型)
  • argsをプリントする(形式は{:?}というデバッグ形式)

clapクレートのbuilderを使うパターン

use clap::{arg, App};

fn main() {
    let matches = App::new("My RPN program")
        .version("1.0.0")
        .author("Your name")
        .about("Super awesome sample RPN calculator")
        .arg(arg!([FILE] "Formulas written in RPN").required(false))
        .arg(arg!(-v --verbose ... "Sets the level of verbosity").required(false))
        .get_matches();

    match matches.value_of("FILE") {
        Some(file) => println!("File specified: {}", file),
        None => println!("No file specified."),
    }
    let verbose = matches.is_present("verbose");
    println!("Is verbosity specified?: {}", verbose);
}
  • My RPN programというAppを作成してmacthesとする
  • versionauthorなどを設定する
  • 必要に応じて、式が書かれたファイルFILEを読み込む
  • 必要に応じて、冗長性verbosityのレベルを変える
  • FILEverboseがあれば、それぞれプリントする

clapクレートのderiveマクロを使うパターン

use clap::Parser;

#[derive(Parser, Debug)]
#[clap(
    name = "My RPN program",
    version = "1.0.0",
    author = "Your name",
    about = "Super awesome sample RPN calculator"
)]
struct Opts {
    /// Sets the level of verbosity
    #[clap(short, long)]
    verbose: bool,

    /// Formulas written in RPN
    #[clap(name = "FILE")]
    formula_file: Option<String>,
}

fn main() {
    let opts = Opts::parse();

    match opts.formula_file {
        Some(file) => println!("File specified: {}", file),
        None => println!("No file specified."),
    }
    println!("Is verbosity specified?: {}", opts.verbose);
}
  • 注記#[clap()]nameversionなどを入力する
  • 構造体Optsを設定する(冗長性verbose、ファイルFILEが要素になる)
  • Opts::parse()でコマンドプロンプトからの入力を受け取りoptsにする
  • matchSome(T)と使って、FILEをプリントする
  • 冗長性verboseをプリントする

Discussion