ユーザーの情報をemailを軸に更新できるようにします。
ついでに、UUIDをつけて後々なにかに使えるようにしときます。
実際のところ
toml
[package] name = "newproject" version = "0.1.0" edition = "2021" [dependencies] clap = { version = "4.5.2", features = ["derive"] } serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" uuid = { version = "1.0", features = ["v4", "serde"] }
スクリプト
パッケージをいれます
use uuid::Uuid;
#[derive(Debug, Subcommand)] enum Commands { //... Update { #[clap(value_parser)] name: String, #[clap(value_parser)] email: String, #[clap(value_parser)] age: u8, } //... }
ユーザーの構造体にもuuidを追加
#[derive(Debug, Serialize, Deserialize)] struct User { id: uuid::Uuid, // name: String, email: String, age: u8, }
// ユーザー追加、UUID対応 fn add_user(&mut self, mut user: User) -> Result<(), String> { // メールアドレスの重複チェック if self.users.iter().any(|u| u.email == user.email) { return Err("Email already exists".to_string()); } // 追加:UUIDを生成して設定 user.id = Uuid::new_v4(); self.users.push(user); Ok(()) } // 更新機能の追加 fn update_user(&mut self, mut user: User) -> Result<(), String> { let existing_user = self.users .iter() .find(|u| u.email == user.email) .ok_or_else(|| "User not found".to_string())?; // 既存のUUIDを保持 user.id = existing_user.id; let user_index = self.users .iter() .position(|u| u.email == user.email) .unwrap(); // ユーザー情報を更新 self.users[user_index] = user; Ok(()) } //... }
あとはUpdateサブコマンドを登録
fn main() { //... Commands::Update { name, email, age } => { let user = User { id: Uuid::new_v4(), name: String::from(name), email: String::from(email), age, }; match db.update_user(user) { Ok(_) => { if let Err(e) = db.save_to_file() { println!("Failed to save database: {}", e); } else { println!("User updated and saved successfully"); } }, Err(e) => println!("Failed to update user: {}", e), } } } }