www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Named tuple from struct

reply Guilherme Vieira <n2.nitrogen gmail.com> writes:
Is is possible to get a named tuple from a struct type?

E.g.:

struct S { int foo; string bar; }

S s;

S.tupleof t; // S.tupleof is a tuple type, as opposed to s.tupleof,
             // which yields a tuple instance

t[0] = 1;
t.bar = "2";


If not, I think it would be quite useful.

Even still, a way to describe tuple types as if it was a struct would also
be useful:

tuple StructLike
{
    int foo;
    string bar;
}

StructLike t;

t[0] = 1;
t.bar = "2";


-- 
Atenciosamente / Sincerely,
Guilherme ("n2liquid") Vieira
Jan 08 2011
parent Jacob Carlborg <doob me.com> writes:
On 2011-01-08 09:15, Guilherme Vieira wrote:
 Is is possible to get a named tuple from a struct type?

 E.g.:

     struct S { int foo; string bar; }

     S s;

     S.tupleof t; // S.tupleof is a tuple type, as opposed to s.tupleof,
                   // which yields a tuple instance

     t[0] = 1;
     t.bar = "2";


 If not, I think it would be quite useful.
You cannot get only the names as a tuple but you can implement something similar: 1. Loop through the tuple 2. Get the name of a field in the struct using the "stringof" property on the tuple 3. Slice of the name of the struct and some other unwanted characters You can have a look at this method as well: http://dsource.org/projects/dstep/browser/dstep/objc/bridge/ClassInitializer.d#L84
 Even still, a way to describe tuple types as if it was a struct would
 also be useful:

     tuple StructLike
     {
          int foo;
          string bar;
     }

     StructLike t;

     t[0] = 1;
     t.bar = "2";


 --
 Atenciosamente / Sincerely,
 Guilherme ("n2liquid") Vieira
-- /Jacob Carlborg
Jan 08 2011