Array literals' default type
Denis Koroskin
2korden at gmail.com
Thu Oct 8 12:10:46 PDT 2009
On Thu, 08 Oct 2009 22:07:32 +0400, Andrei Alexandrescu
<SeeWebsiteForEmail at erdani.org> wrote:
> Consider:
>
> auto c = [ 2.71, 3.14, 6.023e22 ];
> c ~= 2.21953167;
>
> Should this work? Currently it doesn't because c's type is deduced as
> double[3].
>
> The literal can initialize either double[3] or double[], so the question
> is only what the default should be when "auto" is used.
>
>
> Thoughts?
>
> Andrei
I was just about to bump a similar topic.
I strongly believe typeof(c) must be immutable(double)[3].
There are 2 problems in D with current design:
1) The following code:
auto c = [ 2.71, 3.14, 6.023e22 ];
always allocates memory from a heap. In many cases, a read-only view of
that array would suffice. In case a mutation is needed, no one stops you
from dup'ing that array:
auto c = [ 2.71, 3.14, 6.023e22 ].dup;
2) There is an inconsistency with strings:
auto c1 = "Hello"; // immutable
auto c2 = ['H', 'e', 'l', 'l', 'o']; // mutable
I don't like hidden allocations like this to present in D. I believe this
is not what most users expect to happen.
Back to your question, I believe it should be fixed-size and immutable.
Once again, no one stops you from using "[]":
auto c = [ 2.71, 3.14, 6.023e22 ][]; // a slice is returned
The opposite is impossible - you can't get a fixed-sized array from a
dynamic one.
Another question is, what type should .dup return? T[new] or T[]? (The
former one, probably, since the latter one is accessible via .dup[]
syntax...) Anyway, what is the state of T[new] in future of D?
More information about the Digitalmars-d
mailing list