jweinst1
5/9/2019 - 8:03 PM

how to change an enum in rust without returning a new one

how to change an enum in rust without returning a new one

// Rust enum modification example

enum Inventory {
    InStock(f32),
    Out
}

impl Inventory {
    // Here enum is borrowed mutably but does not need to return a new enum to change
    // the val is a reference that can be changed via mutable borrow.
    fn decrease(&mut self) {
        match self {
            Inventory::InStock(val) => *val -= 1.0,
            _ => ()
        }
    }
    
    fn print(&self) {
        match self {
            Inventory::InStock(val) => println!("val is {}", val),
            Inventory::Out => println!("is out")
        }        
    }
}

// Matches struct
fn main() {
    let mut foo = Inventory::InStock(6.6);
    foo.decrease();
    foo.print();
}