/* * Enums in rust * largely copied from https://doc.rust-lang.org/rust-by-example/custom_types/enum.html * ggtowell * Nov 2023 */ enum WebEvent { PageLoad, PageUnload, KeyPress(char), // an enum can have values!! Paste(String), Clunk(i32, i32), // more than one! Click { x: i64, y: i64 }, // it can even be an anonymous struct } // A function which takes a `WebEvent` enum as an argument and // returns nothing. fn inspect(event: WebEvent) { // match is smart on enum -- compiler will fail is not every one is listed match event { WebEvent::PageLoad => println!("page loaded"), WebEvent::PageUnload => println!("page unloaded"), // Destructure `c` from inside the `enum` variant. WebEvent::KeyPress(c) => println!("pressed '{}'.", c), WebEvent::Paste(s) => println!("pasted \"{}\".", s), // Destructure `Click` into `x` and `y`. WebEvent::Click { x, y } => { println!("clicked at x={}, y={}.", x, y); }, WebEvent::Clunk(x,y) => println!("Clunk x={x} y={y}"), } } fn main() { let pressed = WebEvent::KeyPress('x'); // `to_owned()` creates an owned `String` from a string slice. let pasted = WebEvent::Paste(String::from("my text")); let click = WebEvent::Click { x: 20, y: 80 }; let load = WebEvent::PageLoad; let unload = WebEvent::PageUnload; let clunk = WebEvent::Clunk(1,2); inspect(pressed); inspect(pasted); inspect(click); inspect(load); inspect(unload); inspect(clunk); }