chasahodge
chasahodge

Reputation: 443

How do I get the value from an enum in a vec?

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?

Upvotes: 0

Views: 408

Answers (2)

chasahodge
chasahodge

Reputation: 443

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!

Upvotes: 0

Aunmag
Aunmag

Reputation: 962

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

Upvotes: 1

Related Questions