Skip to content

Instantly share code, notes, and snippets.

@byigitt
Created June 4, 2025 16:03
Show Gist options
  • Select an option

  • Save byigitt/2ad04639eec5a0f7bf581a8c494d8d5c to your computer and use it in GitHub Desktop.

Select an option

Save byigitt/2ad04639eec5a0f7bf581a8c494d8d5c to your computer and use it in GitHub Desktop.
rust basic homework
struct Customer {
name: String,
surname: String,
balance: f64,
}
struct Product {
name: String,
price: f64,
stock: u32,
}
impl Customer {
fn buy_product(&mut self, product: &mut Product, quantity: u32) -> bool {
let total_cost = product.price * quantity as f64;
if product.stock >= quantity && self.balance >= total_cost {
self.balance -= total_cost;
product.stock -= quantity;
true
} else {
false
}
}
}
fn main() {
let mut customer1 = Customer {
name: String::from("Alice"),
surname: String::from("Smith"),
balance: 100.0,
};
let mut customer2 = Customer {
name: String::from("Bob"),
surname: String::from("Johnson"),
balance: 50.0,
};
let mut product1 = Product {
name: String::from("Laptop"),
price: 1200.0,
stock: 10,
};
let mut product2 = Product {
name: String::from("Mouse"),
price: 25.0,
stock: 50,
};
println!("Initial state:");
println!("Customer 1: {} {}, Balance: ${:.2}", customer1.name, customer1.surname, customer1.balance);
println!("Customer 2: {} {}, Balance: ${:.2}", customer2.name, customer2.surname, customer2.balance);
println!("Product 1: {}, Price: ${:.2}, Stock: {}", product1.name, product1.price, product1.stock);
println!("Product 2: {}, Price: ${:.2}, Stock: {}", product2.name, product2.price, product2.stock);
println!("------------------------------------");
println!("Customer 1 is trying to buy 1 Laptop...");
if customer1.buy_product(&mut product1, 1) {
println!("Customer 1 successfully purchased Laptop.");
} else {
println!("Customer 1 couldn't purchase Laptop. (Not enough balance or stock)");
}
println!("Customer 1 Balance: ${:.2}, Product 1 Stock: {}", customer1.balance, product1.stock);
println!("------------------------------------");
println!("Customer 2 is trying to buy 2 Mice...");
if customer2.buy_product(&mut product2, 2) {
println!("Customer 2 successfully purchased 2 Mice.");
} else {
println!("Customer 2 couldn't purchase 2 Mice. (Not enough balance or stock)");
}
println!("Customer 2 Balance: ${:.2}, Product 2 Stock: {}", customer2.balance, product2.stock);
println!("------------------------------------");
println!("Customer 1 is trying to buy 10 Mice...");
if customer1.buy_product(&mut product2, 10) {
println!("Customer 1 successfully purchased 10 Mice.");
} else {
println!("Customer 1 couldn't purchase 10 Mice. (Not enough balance or stock)");
}
println!("Customer 1 Balance: ${:.2}, Product 2 Stock: {}", customer1.balance, product2.stock);
println!("------------------------------------");
println!("Customer 2 is trying to buy 1 Laptop (should fail)...");
if customer2.buy_product(&mut product1, 1) {
println!("Customer 2 successfully purchased Laptop.");
} else {
println!("Customer 2 couldn't purchase Laptop. (Not enough balance or stock)");
}
println!("Customer 2 Balance: ${:.2}, Product 1 Stock: {}", customer2.balance, product1.stock);
println!("------------------------------------");
// User interface loop
// For simplicity, we'll use a predefined list of customers and products.
// In a real application, you might want to manage these dynamically.
let mut customers = vec![
Customer { name: String::from("Charlie"), surname: String::from("Brown"), balance: 200.0 },
Customer { name: String::from("Diana"), surname: String::from("Prince"), balance: 1500.0 },
];
let mut products = vec![
Product { name: String::from("Keyboard"), price: 75.0, stock: 20 },
Product { name: String::from("Monitor"), price: 300.0, stock: 15 },
Product { name: String::from("Webcam"), price: 50.0, stock: 30 },
];
loop {
println!("
Market Operations:");
println!("1. List Customers");
println!("2. List Products");
println!("3. Make a Purchase");
println!("4. Exit");
print!("Enter your choice: ");
// Flush stdout to ensure the prompt is displayed before reading input
use std::io::{self, Write};
io::stdout().flush().unwrap();
let mut choice = String::new();
io::stdin().read_line(&mut choice).expect("Failed to read line");
let choice: u32 = match choice.trim().parse() {
Ok(num) => num,
Err(_) => {
println!("Invalid input. Please enter a number.");
continue;
}
};
match choice {
1 => {
println!("
Customers:");
for (i, customer) in customers.iter().enumerate() {
println!("{}. {} {} - Balance: ${:.2}", i + 1, customer.name, customer.surname, customer.balance);
}
}
2 => {
println!("
Products:");
for (i, product) in products.iter().enumerate() {
println!("{}. {} - Price: ${:.2} - Stock: {}", i + 1, product.name, product.price, product.stock);
}
}
3 => {
println!("
Select Customer:");
for (i, customer) in customers.iter().enumerate() {
println!("{}. {} {}", i + 1, customer.name, customer.surname);
}
print!("Enter customer number: ");
io::stdout().flush().unwrap();
let mut cust_idx_str = String::new();
io::stdin().read_line(&mut cust_idx_str).expect("Failed to read line");
let cust_idx: usize = match cust_idx_str.trim().parse() {
Ok(num) => num,
Err(_) => {
println!("Invalid customer number.");
continue;
}
};
if cust_idx == 0 || cust_idx > customers.len() {
println!("Invalid customer selection.");
continue;
}
let cust_idx = cust_idx -1; // Adjust to 0-based index
println!("
Select Product:");
for (i, product) in products.iter().enumerate() {
println!("{}. {} (Stock: {})", i + 1, product.name, product.stock);
}
print!("Enter product number: ");
io::stdout().flush().unwrap();
let mut prod_idx_str = String::new();
io::stdin().read_line(&mut prod_idx_str).expect("Failed to read line");
let prod_idx: usize = match prod_idx_str.trim().parse() {
Ok(num) => num,
Err(_) => {
println!("Invalid product number.");
continue;
}
};
if prod_idx == 0 || prod_idx > products.len() {
println!("Invalid product selection.");
continue;
}
let prod_idx = prod_idx -1; // Adjust to 0-based index
print!("Enter quantity: ");
io::stdout().flush().unwrap();
let mut quantity_str = String::new();
io::stdin().read_line(&mut quantity_str).expect("Failed to read line");
let quantity: u32 = match quantity_str.trim().parse() {
Ok(num) => num,
Err(_) => {
println!("Invalid quantity.");
continue;
}
};
if customers[cust_idx].buy_product(&mut products[prod_idx], quantity) {
println!("Purchase successful! {} {} bought {} of {}.", customers[cust_idx].name, customers[cust_idx].surname, quantity, products[prod_idx].name);
println!("New balance: ${:.2}. Remaining stock for {}: {}.", customers[cust_idx].balance, products[prod_idx].name, products[prod_idx].stock);
} else {
println!("Purchase failed. Check balance and product stock.");
}
}
4 => {
println!("Exiting market system.");
break;
}
_ => {
println!("Invalid choice. Please try again.");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment