Created
September 13, 2018 06:28
-
-
Save jafow/1e172bc89459db788348cce92d562b01 to your computer and use it in GitHub Desktop.
A Vec of Enums containing different types
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn main() { | |
// make a type Cell that contains a few different primitive types | |
enum Cell { | |
Text(String), | |
Num(i32), | |
Float(f32) | |
} | |
// make a list of them | |
let row = vec![ | |
Cell::Text(String::from("ItemID")), | |
Cell::Text(String::from("CustomerID")), | |
Cell::Num(42), | |
Cell::Float(99.99), | |
Cell::Text(String::from("City")) | |
]; | |
// iterate over the list and do something with the values | |
let mut sum: f32 = 0.0; | |
let mut qty: i32 = 1; | |
let mut customer_data = String::new(); | |
for x in row.iter() { | |
match x { | |
Cell::Text(s) => customer_data.push_str(s), | |
Cell::Num(n) => qty *= n, | |
Cell::Float(n) => sum += n, | |
} | |
} | |
assert_eq!(customer_data, "ItemIDCustomerIDCity"); | |
assert_eq!(sum, 99.99); | |
assert_eq!(qty, 42); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment