Problem overview
You build a VendingMachine struct for a machine that sells one kind of item at a fixed price. The machine remembers the money inserted so far, called the credit. A new machine has credit: 0.0 and price: 150.0, both f64 fields, created with VendingMachine::new().
Three methods change or report that state:
insert(&mut self, amount: f64)adds the amount to the credit and returns nothing.select(&mut self) -> Stringtries to buy one item. If the credit is below the price it returns"Need N more"(N is the missing amount as a whole number) and changes nothing. Otherwise it subtracts the price from the credit and returns"Dispensing!". Exact payment works, and any extra money stays as credit.refund(&mut self) -> f64returns the whole credit and sets it back to 0.
The starter code supplies the driver. Inserting 50 is not enough, so the machine asks for 100 more. Inserting 150 more makes 200, so it dispenses and keeps 50, and the refund is 50. Exact payment of 150 dispenses and refunds 0. Inserting 100 is 50 short, and the refund is 100. The expected output is:
Need 100 more
Dispensing!
Refunded: 50
Dispensing!
Refunded: 0
Need 50 more
Refunded: 100
Approach: state plus rules
The two fields are the whole state of the machine. Each method reads or changes them according to one rule:
insertonly adds to the credit.selectcompares the credit with the price. It has two outcomes, and only the success path touches the credit.refundhands back the credit and clears it.
Because every machine made by new() has its own copy of the fields, two machines never share credit.
Step by step
- Declare the struct
VendingMachine. - Add
credit: f64, the money inserted so far. - Add
price: f64, the cost of one item. - Open
impl VendingMachinefor all the methods. - Write
newwith no parameters, returning aVendingMachine. Rust has no special constructors, sonewis a plain function by convention. - Start the struct literal as the last expression of
new, with no semicolon. - Set
creditto0.0. Write the decimal point, because a bare0is an integer and doesn't fit anf64field. - Set
priceto150.0. - Write
insertwith&mut selfandamount: f64. - Add to the credit with
self.credit += amount. Adding keeps what was already inserted. - Write
selectwith&mut self, returning aString. - Test for too little money:
if self.credit < self.price. Because the test is<, a credit equal to the price passes it. - Return the message from inside the
if:format!builds aString, and(self.price - self.credit) as i32turns the missing amount into a whole number. The credit isn't touched. - Subtract the price from the credit after the
if. This runs only when the credit covered the price. - End with
"Dispensing!".to_string(), with no semicolon, so it is the returned value. A string literal is a&str, and the method returns an ownedString. - Write
refundwith&mut self, returning anf64. - Save the credit in
rfirst. - Reset
self.creditto0.0. - Finish with
ralone, so the saved amount is returned.
The solution in Rust
struct VendingMachine {
credit: f64,
price: f64,
}
impl VendingMachine {
fn new() -> VendingMachine {
VendingMachine {
credit: 0.0,
price: 150.0,
}
}
fn insert(&mut self, amount: f64) {
self.credit += amount;
}
fn select(&mut self) -> String {
if self.credit < self.price {
return format!("Need {} more", (self.price - self.credit) as i32);
}
self.credit -= self.price;
"Dispensing!".to_string()
}
fn refund(&mut self) -> f64 {
let r = self.credit;
self.credit = 0.0;
r
}
}
fn mainFunction() {
let mut m = VendingMachine::new();
m.insert(50.0);
println!("{}", m.select());
m.insert(150.0);
println!("{}", m.select());
println!("Refunded: {}", m.refund() as i32);
m.insert(150.0);
println!("{}", m.select());
println!("Refunded: {}", m.refund() as i32);
m.insert(100.0);
println!("{}", m.select());
println!("Refunded: {}", m.refund() as i32);
}
Language details
- Why
refundsaves the credit first. Afterself.credit = 0.0, the old amount is gone. Returningself.creditat that point would always return 0:
fn refund(&mut self) -> f64 {
self.credit = 0.0;
self.credit
}
With 50 of credit, this version returns 0. Saving into r keeps the amount alive until the return.
format!versusprintln!.format!builds aStringusing the same{}placeholders, and returns it instead of printing.- Printing
f64values.{}shows100.0as100, so even without a cast the message would readNeed 100 more. The lesson still usesas i32to make the amount a whole number. - The cast truncates.
as i32drops the fractional part. With a credit of 149.5, the missing amount is 0.5 and the message isNeed 0 more. The lesson's inputs are whole numbers, so this doesn't show up in the tests. - Early
returnversus a final expression. The failing branch usesreturn ...;because it leaves the function early. The last line is a bare expression with no semicolon.
Edge cases and common mistakes
- Exact payment. Inserting exactly 150 must dispense. Using
<=in the check would refuse it. - Subtracting too early. If the price is subtracted before the check, a failed purchase still shrinks the credit.
- Forgetting to subtract. If the price isn't subtracted on success, the leftover credit is too big, and so is the refund. In the driver, the first refund would be 200 instead of 50.
- Credit for several items. With 300 inserted, three calls to
selectreturnDispensing!,Dispensing!and thenNeed 150 more: each success uses 150, and the credit is 0 by the third call. - Refund twice. The second
refundin a row returns 0, because the first one cleared the credit. - Money as floats. An
f64can't store most decimal fractions exactly, so amounts like 0.1 add up with tiny errors. Whole-number amounts, as here, are exact.
Key takeaways
- A struct's fields are its state, and methods taking
&mut selfchange that state. - Check the condition before changing anything, so a failed request leaves the state as it was.
- When a method must both reset a field and return its old value, save the value in a local variable first.
