[:] as empty associative array literal, plus warning for null

monarch_dodra monarchdodra at gmail.com
Thu Jul 4 05:52:39 PDT 2013


On Thursday, 4 July 2013 at 12:42:51 UTC, Timon Gehr wrote:
> On 07/04/2013 01:50 PM, Steven Schveighoffer wrote:
>> On Thu, 04 Jul 2013 05:25:30 -0400, Regan Heath 
>> <regan at netmail.co.nz>
>> wrote:
>>
>>> On Wed, 03 Jul 2013 19:10:40 +0100, bearophile
>>> <bearophileHUGS at lycos.com> wrote:
>>>> Telling apart the literal for an empty array from the 
>>>> literal of a
>>>> empty but not null array is a bad idea that muds the 
>>>> language. And
>>>> thankfully this currently fails:
>>>>
>>>> void main() {
>>>>     int[] emptyArray = [];
>>>>     assert(emptyArray !is null);
>>>> }
>>>
>>> As this comes up often you're probably aware that there are 
>>> people
>>> (like myself) who find the distinction between a null 
>>> (non-existant)
>>> array and an empty array useful.
>>
>> Nobody questions that.  The biggest problem is making if(arr) 
>> mean
>> if(arr.ptr) instead of if(arr.length)
>>
>
> if(arr.ptr) is what it means now.
>
>> What [] returns should not be an allocation.  And returning 
>> null is a
>> reasonable implementation of that.
>>
>> -Steve
>
> static __gshared void[1] x;
> return x[0..0];

+1. If you really want null, you can just as well use null for 
typeless, or "T[].init" for strong typing.

As stated before:
> Reasoning by extrapolation:
> int[] arr = [1, 2, 3]; // Array of 3 ints
> int[] arr = [1, 2]; // Array of 2 ints
> int[] arr = [1]; // Array of 1 ints
> int[] arr = []; // Array of 0 ints (not null)

As demonstrated this can be done with no allocations either.


More information about the Digitalmars-d mailing list