Start learning free

LESSON 67 OF 69 · PROJECTS: OBJECT-ORIENTED

Vending Machine in Rust: A Struct with State and Methods

Practice Read the full explanation

Build a VendingMachine type (a struct with methods) for a machine that sells one kind of item for a fixed price. It keeps the money inserted so far (the credit), sells an item when the credit is enough, and gives the remaining credit back on request. A new object is made with VendingMachine::new().

Rules:

  • State. A new machine has credit 0 and price 150 (every item costs 150). Give the struct the fields credit: f64 and price: f64; fn new() returns VendingMachine { credit: 0.0, price: 150.0 }.
  • fn insert(&mut self, amount: f64) adds amount to the credit. Nothing is printed or returned.
  • fn select(&mut self) -> String tries to buy one item and returns a string:
    • If the credit is less than the price, return "Need N more", where N is the missing amount (price - credit) as a whole number, for example "Need 100 more". The credit does not change.
    • Otherwise (the credit is equal to or greater than the price, so exact payment works), subtract the price from the credit and return "Dispensing!". Any extra money stays in the credit.
  • fn refund(&mut self) -> f64 returns the whole credit and sets it back to 0, so asking again right away returns 0.

You start with this driver below your code:

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);
}

Walk through it: 50 is not enough, so you see Need 100 more. After 150 more the credit is 200, so the machine dispenses and keeps 50 (200 - 150), and the refund is 50. Then 150 is exact payment: it dispenses and the refund is 0. Finally 100 is short by 50, the credit stays 100, and the refund is 100.

Expected output:

Need 100 more
Dispensing!
Refunded: 50
Dispensing!
Refunded: 0
Need 50 more
Refunded: 100

Convert the missing amount with (self.price - self.credit) as i32 and build the text with format!("Need {} more", ...). Do the subtraction only when the item is dispensed, not when the credit is too low. If you forget it, the leftover credit is wrong and the refund is too big.

In the refund method, save the credit first, then reset it to 0, then return what you saved. Return the saved variable, not self.credit.

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
    }
}

STEP 1 OF 19
    Ctrl + Enter to check

    RUST · PROJECTS: OBJECT-ORIENTED

    Vending Machine in Rust, explained

    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) -> String tries 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) -> f64 returns 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:

    • insert only adds to the credit.
    • select compares the credit with the price. It has two outcomes, and only the success path touches the credit.
    • refund hands 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

    1. Declare the struct VendingMachine.
    2. Add credit: f64, the money inserted so far.
    3. Add price: f64, the cost of one item.
    4. Open impl VendingMachine for all the methods.
    5. Write new with no parameters, returning a VendingMachine. Rust has no special constructors, so new is a plain function by convention.
    6. Start the struct literal as the last expression of new, with no semicolon.
    7. Set credit to 0.0. Write the decimal point, because a bare 0 is an integer and doesn't fit an f64 field.
    8. Set price to 150.0.
    9. Write insert with &mut self and amount: f64.
    10. Add to the credit with self.credit += amount. Adding keeps what was already inserted.
    11. Write select with &mut self, returning a String.
    12. Test for too little money: if self.credit < self.price. Because the test is <, a credit equal to the price passes it.
    13. Return the message from inside the if: format! builds a String, and (self.price - self.credit) as i32 turns the missing amount into a whole number. The credit isn't touched.
    14. Subtract the price from the credit after the if. This runs only when the credit covered the price.
    15. 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 owned String.
    16. Write refund with &mut self, returning an f64.
    17. Save the credit in r first.
    18. Reset self.credit to 0.0.
    19. Finish with r alone, 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 refund saves the credit first. After self.credit = 0.0, the old amount is gone. Returning self.credit at 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! versus println!. format! builds a String using the same {} placeholders, and returns it instead of printing.
    • Printing f64 values. {} shows 100.0 as 100, so even without a cast the message would read Need 100 more. The lesson still uses as i32 to make the amount a whole number.
    • The cast truncates. as i32 drops the fractional part. With a credit of 149.5, the missing amount is 0.5 and the message is Need 0 more. The lesson's inputs are whole numbers, so this doesn't show up in the tests.
    • Early return versus a final expression. The failing branch uses return ...; 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 select return Dispensing!, Dispensing! and then Need 150 more: each success uses 150, and the credit is 0 by the third call.
    • Refund twice. The second refund in a row returns 0, because the first one cleared the credit.
    • Money as floats. An f64 can'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 self change 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.
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free