mixed type list?

Jonathan M Davis jmdavisProg at gmx.com
Wed Nov 20 03:25:13 PST 2013


On Wednesday, November 20, 2013 12:07:25 seany wrote:
> Is there any way to represent mixed data (of various types) as a
> single array?
> 
> In scilab, we have list, and you can do list(integer, stringvar
> ....) etc.
> 
> Can you do something similar in D?  An idea is to use a struct
> wil all possible data types, but think that is inefficient.
> 
> Any other ideas?

That sounds more like a tuple rather than a list, as lists normally are 
supposed to contain values which all have the same type. So, the normal thing 
to do would probably be to use std.typecons.Tuple. e.g.

auto t = tuple(1, 3.7, "foo");

But that's definitely a tuple and not a list, so you can't append to it or 
remove anything from it or anything like that. If you want an actual list, you 
need a way to make all of the items in the list be the same type. And if they 
don't all share a base type (which pretty much only happens with classes), 
then you'd probably have to use std.variant.Variant, which is essentially a 
typed union. However, I'd advise against using anything like that unless you 
actually need it. You should favor static typing as much as possible rather 
than trying to hold differing types in the same list, as that's just begging 
for bugs, particularly when you then try and use some of those items as a type 
other than what they are.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list