経緯
ふと、 Rust で書いたプログラムで曜日判定を追加したくなったのでやってみました。
コード
早速ですがコードを。
data.rs
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize, Debug)]
pub struct Target {
pub label: String,
pub weekjudge: u32,
}
pub fn listup() -> Vec<Target> {
let mut files: Vec<Target> = Vec::new();
files.push(Target {
label: String::from("Every"),
weekjudge: 7,
});
files.push(Target {
label: String::from("Apollo"),
weekjudge: 0,
});
}
例えばこういう自前のベクタ型を用意して
main.rs
use chrono::Local;
fn get_list_info() -> Vec<Info> {
// モジュール化したコードから想定しているリストを取得
let list: Vec<Target> = listup();
// 結果のベクターを初期化
let mut result: Vec<Info> = Vec::new();
// 想定しているファイル一覧をループ
for item in list {
if item.weekjudge == 7 || item.weekjudge == current_time.date().weekday().num_days_from_sunday() {
result.push(Info {
label: String::from(&item.label),
status: String::from("OK"),
});
}
}
if result.iter().find(|e| &e.label==&item.label).is_none() {
// 結果リストに label の名前がない場合
let current_time = chrono::offset::Local::now();
if item.weekjudge != current_time.date().weekday().num_days_from_sunday() && item.weekjudge != 7 {
// 該当アイテムの曜日判定が今日の曜日ではない場合は「該当曜日以外の曜日」という正常の無し判定
result.push(Info {
label: String::from(&item.label),
status: String::from("NoCheck"),
});
} else {
// そうでない場合はエラーの無し判定
result.push(Info {
label: String::from(&item.label),
status: String::from("Nothing"),
});
}
}
}
関係ある部分のみを抜粋するとざっとこんな感じ。
chrono::Local
のクレートを読み込んで、 chrono::offset::Local::now()
で現在日時を取得。
current_time
に代入し、その current_time
に対して current_time.date().weekday().num_days_from_sunday()
で日曜日を0として起算した曜日の数値を、判定用の自前ベクタ型が持つ weekjudge
プロパティに突き合わせする、という寸法。
これでやりたいことは実現できました。
参考
Rust の日時
- date – How can I get the current weekday in Rust using the Chrono crate? – Stack Overflow
- Rustの時間に関するクレート2:chronoメモ [blessed.rsシリーズ28]
- 祝日を計算しようと思ったら闇が深かった話 #Rust – Qiita
- 今回は祝日は扱う必要はなかったがメモ。
if文
Rust、論理和や論理積については左側が真だとそこで評価を終えてしまって、右側を評価しないのですね……。最初個々に引っかかりそうになりました。