简体   繁体   English

如何从 vec 中的枚举中获取值?

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

I have an enum defined as shown below (TableCell).我定义了一个枚举,如下所示(TableCell)。 I then create a Vec (row) and push a TableCell into the the row.然后我创建一个 Vec(行)并将一个 TableCell 推入该行。 I then have another Vec (table_data) which I push the row into.然后我有另一个 Vec (table_data) 我将行推入。 Finally I do an output of the values stored in table_data:最后,我对 table_data 中存储的值执行 output:

#[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).我的 output 显示为 Float(1000.00)。 How do I get just the 1000.00?我怎样才能得到 1000.00?

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

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.因为“值”的计算结果为 vec(即行变量),所以我必须遍历行中的所有 TableCells 以获得实际值。

Thanks to everyone who suggested a solution, they all helped!感谢所有提出解决方案的人,他们都提供了帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM