The point is to add an implicit conversion rule so that
associative array literals can efficiently be passed
to a function.
Similar to how array literals could be passed on the stack (see bug 11657),
the AA literal elements could be passed as tuples.
----
MyAA!(Key, Value) myAA(Key, Value)(AATuple!(Key, Value)[] elems...)
{
}
unittest
{
auto aa = myAA(["foo" : 0, "bar" : 1]);
}
----
It might be cleaner to generally allow the AA to array literal conversion.
----
AATuple!(string, int)[] ary = ["foo" : 0, "bar" : 1];
----
In lack of a standard tuple type we'd need to define a simple
struct AATuple(Key, Value) { Key key; Value value; }
in object.
NB:
This should only apply to literals.
Comment #1 by wazar.leollone — 2013-12-01T13:46:07Z
IMO, it's more then need to AA and less then need to user types.
First AA literal usage that I see is an JSONValue initialization:
JSONValue var = [
"Key1":42L,
"Key2":"foo",
"Key3":[1, "bar", 12.7]
];
I suggest another way to implement this feature.
1. declare in in object two structs:
struct AssociativeArrayLiteral(T...)
{
//void
}
struct ArrayLiteral(T...)
{
//void
}
2. Allow converting [a:b, c:d] to AssociativeArrayLiteral!(a, b, c, d)() and [a, b, c, d] to ArrayLiteral!(a, b, c)
3. User can implement his type like the following:
struct MyJSON
{
this(T)(T var)
{
static if(is(T : AssociativeArrayLiteral!TL, TL...))
{
pragma(msg, TL.stringof); //TL is an expanded AA-literal tuple
}
else
{
static assert(0);
}
}
}
4. By default [a:[b,c,d]] should converts to associative array with key `a` and D-array value [b,c,d], but if outer literal boxed to AssociativeArrayLiteral, inner literal should be boxed to ArrayLiteral without attempting to represent it as standart D array, even if it possible. If a user wants to control parsing of outer literal manually then only he knows how to parse inner literals.
Comment #2 by code — 2013-12-01T16:03:45Z
That would work as well, but it has some drawbacks.
- Template bloat for different AA/array lengths.
- Typing rules depends on the implementation, which allows
subtle surprises.
- AA/array literals with mixed types are debatable but not necessary
to implement a library AA. Better discuss this idea on the newsgroup.
Comment #3 by code — 2013-12-13T10:29:09Z
Let me restate the last point.
I think it's better that we don't conflate adding a library AA with
altering the language AA literals to be usable for other purposes.
Keeping things orthogonal helps to stay focused and increases the likeliness of merging a change.
Comment #4 by robert.schadek — 2024-12-13T18:14:47Z