dynamic get from variantArray() data table
Alex Parrill via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Oct 13 08:51:38 PDT 2015
On Tuesday, 13 October 2015 at 15:17:15 UTC, data pulverizer
wrote:
> Hi,
>
> I am trying to use variantArray() as a data table object to
> hold columns each of which is an array of a specific type. I
> need to be able to get values from data table but I am having
> problems ...
>
>
> import std.stdio; // i/o
> import std.variant; // type variations
>
> void main(){
> // Columns of the table
> string[] names = ["walter", "paul", "jeff", "andrie"];
> int[] age = [55, 62, 27, 52];
> string[] language = ["D", "Haskell", "Julia", "D"];
> Variant[] dt = variantArray(names, age, language);
>
> foreach(col; dt){
> foreach(el; col){
> // here I try a kind of dynamic cast operator
> auto x = el.get!(type(el)); // gives error
> write(x);
> }
> write("\n");
> }
> }
>
> data_table.d(37): Error: cannot infer type for el
> data_table.d(38): Error: undefined identifier 'el'
>
> Help
>
> DP
You're trying to iterate over a `Variant`, which isn't
implemented.
You don't want to use a variant here anyway; you should use a
struct or tuple for each entry in the table.
import std.typecons;
alias Entry = Tuple!(string, int, string);
void main() {
auto table = [Entry("walter", 55, "D"), Entry("paul", 62,
"Haskell"), ... ]; // complete array
foreach(entry; table) {
writeln(entry.expand);
}
}
More information about the Digitalmars-d-learn
mailing list