1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
| use std::collections::HashMap; use std::fmt;
#[derive(Debug, Clone)] struct Book { id: u32, title: String, author: String, price: f64, quantity: u32, }
impl Book { fn new(id: u32, title: &str, author: &str, price: f64, quantity: u32) -> Self { Book { id, title: title.to_string(), author: author.to_string(), price, quantity, } } }
impl fmt::Display for Book { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "ID: {}, Title: '{}', Author: '{}', Price: ${:.2}, Quantity: {}", self.id, self.title, self.author, self.price, self.quantity ) } }
struct InventoryManager { books_by_id: HashMap<u32, Book>, books_by_title: HashMap<String, Vec<u32>>, next_id: u32, }
impl InventoryManager { fn new() -> Self { InventoryManager { books_by_id: HashMap::new(), books_by_title: HashMap::new(), next_id: 1, } }
fn add_book(&mut self, title: &str, author: &str, price: f64, quantity: u32) { let id = self.next_id; self.next_id += 1; let book = Book::new(id, title, author, price, quantity); self.books_by_id.insert(id, book.clone()); self.books_by_title .entry(title.to_lowercase()) .or_insert_with(Vec::new) .push(id); println!("Added book: {}", book); }
fn find_by_id(&self, id: u32) -> Option<&Book> { self.books_by_id.get(&id) }
fn find_by_title(&self, title: &str) -> Vec<&Book> { let title_lower = title.to_lowercase(); self.books_by_title .get(&title_lower) .map(|ids| { ids.iter() .filter_map(|id| self.books_by_id.get(id)) .collect() }) .unwrap_or_else(Vec::new) }
fn update_quantity(&mut self, id: u32, delta: i32) -> Result<(), String> { if let Some(book) = self.books_by_id.get_mut(&id) { let new_quantity = book.quantity as i32 + delta; if new_quantity < 0 { return Err(format!( "Cannot update quantity for book ID {}. Negative quantity not allowed.", id )); } book.quantity = new_quantity as u32; println!("Updated book ID {}: new quantity = {}", id, book.quantity); Ok(()) } else { Err(format!("Book with ID {} not found", id)) } }
fn remove_book(&mut self, id: u32) -> Result<(), String> { if let Some(book) = self.books_by_id.remove(&id) { if let Some(ids) = self.books_by_title.get_mut(&book.title.to_lowercase()) { ids.retain(|&book_id| book_id != id); if ids.is_empty() { self.books_by_title.remove(&book.title.to_lowercase()); } } println!("Removed book: {}", book); Ok(()) } else { Err(format!("Book with ID {} not found", id)) } }
fn list_all_books(&self) { println!("\n--- Inventory Report ---"); if self.books_by_id.is_empty() { println!("No books in inventory"); return; } for book in self.books_by_id.values() { println!("{}", book); } println!("Total books: {}", self.books_by_id.len()); } }
fn main() { let mut inventory = InventoryManager::new();
inventory.add_book("The Rust Programming Language", "Steve Klabnik", 39.99, 10); inventory.add_book("Programming Rust", "Jim Blandy", 49.99, 5); inventory.add_book("Rust in Action", "Tim McNamara", 44.99, 8); inventory.add_book("The Rust Programming Language", "Carol Nichols", 39.99, 15);
println!("\nSearching for books by title 'Rust':"); for book in inventory.find_by_title("Rust") { println!("- {}", book); } println!("\nSearching for book ID 2:"); if let Some(book) = inventory.find_by_id(2) { println!("- {}", book); }
println!("\nUpdating stock:"); inventory.update_quantity(1, -3).unwrap(); inventory.update_quantity(1, 5).unwrap();
match inventory.update_quantity(1, -20) { Ok(_) => {} Err(e) => println!("Error: {}", e), }
println!("\nRemoving book ID 3:"); inventory.remove_book(3).unwrap();
inventory.list_all_books();
match inventory.remove_book(99) { Ok(_) => {} Err(e) => println!("\nError: {}", e), } }
|