Struct with flexible amount of attributes

I want to create a struct to create a CSV file later on. The amount of "columns" is flexible though, because columns store data for specific months, like this:

ID Sep 2024 Aug 2024 ...
x 234 643 ...
y 456 392 ...

So depending on when the tool runs, it varies regarding the amount of columns.

Is there a way to create such flexible struct? I guess the alternative would be so work with a vector for each row

Sure, you'll likely want a table with a column-major layout, eg

struct FlexyTable {
   columns: Vec<Vec<CellData>>, 
}

Where CellData is the data type that defines each cell.

With that you can easily create new columns (i.e. flexy_table.push(new_column)), and adding rows is a little more involved but still perfectly possible.

In your suggested solution, the amount of attributes are not flexible, it's just one single attribute. But I guess that's how it needs to be done! thank you!

You can use an enum:

enum CellData {
    Float(f64),
    Int(isize),
    String(String),
}

Or make it a generic type:

struct FlexyTable<T> {
    columns: Vec<Vec<T>>,
}

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.