0

I have an enum defined as shown below (TableCell). I then create a Vec (row) and push a TableCell into the the row. I then have another Vec (table_data) which I push the row into. Finally I do an output of the values stored in table_data:

#[derive(Debug)]
enum TableCell {
    Label(String),
    Float(f32),
}

let mut row = vec![];

row.push(TableCell::Float(client_budget.cost)); //(client_budget.cost = 1000.00)

let mut table_data = Vec::new();

table_data.push(row);

for value in table_data.iter() {
    println!("{:#?}", value)
}

My output comes out as Float(1000.00). How do I get just the 1000.00?

chasahodge
  • 373
  • 1
  • 4
  • 11
  • Does this answer your question? [Unwrap inner type when enum variant is known](https://stackoverflow.com/questions/34953711/unwrap-inner-type-when-enum-variant-is-known) – Ted Klein Bergman Aug 09 '20 at 22:57
  • 1
    If you don't like the default derivation of `Debug`, either implement it yourself, or use a crate with [a different derivation](https://mcarton.github.io/rust-derivative/Debug.html#hiding-newtypes). – mcarton Aug 09 '20 at 23:06
  • Ted: Not sure I fully understand how to apply for your comment but I tried both row.push(TableCell::Float(client_budget.cost).unwrap()) and row.push(TableCell::Float(client_budget.cost.unwrap())), both have compile errors. – chasahodge Aug 09 '20 at 23:16
  • Mcarton: How would I do that? I’m new to rust. A link to something I can read? – chasahodge Aug 09 '20 at 23:23
  • 1
    See the [Patterns that Bind to Values](https://doc.rust-lang.org/book/ch06-02-match.html#patterns-that-bind-to-values) section of The Rust Programming Language. – eggyal Aug 09 '20 at 23:37

2 Answers2

1

You can do

// ...

for value in table_data.iter() {
    if let TableCell::Float(float) = value {
        println!("{}", float);
    }
}

Or if you need print both:

for value in table_data.iter() {
    match value {
        TableCell::Label(label) => println!("{}", label),
        TableCell::Float(float) => println!("{}", float),
    }
}
Aunmag
  • 852
  • 12
  • 17
0

After reading everyone's comments and studying their suggestions I finally figured out the solution:

for value in table_data {
    for cell in value {
        match cell {
            TableCell::Label(label) => println!("{}", label),
            TableCell::Float(float) => println!("{}", float),
        }
    }
}

because "value" evaluates to a vec (which is the row variable) I had to iterate through all of the TableCells in the row to get at the actual values.

Thanks to everyone who suggested a solution, they all helped!

chasahodge
  • 373
  • 1
  • 4
  • 11