Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using a local clone.

Static array literals

Version 1
Created 2013-04-06
StatusDraft
Last modified 2013-04-06
Author Timothee Cour

Abstract

This is a proposal for introducing static array literals, as follows:

   auto x=[1,2,3]S; 
   static assert(is(typeof(x)==int[3]));

The particular choice of ‘S’ can be discussed.

Description

Currently, array literals such as

   auto x=[1,2,3];

make x dynamic. To get a static array one needs to write:

   int[3] x=[1,2,3];

which is inconvenient for many reasons:

- it’s not DRY (need to explicitly write 3 as the length and specify the type int) - there’s no easy way to pass a static array literal to a function accepting a static array; for example it requires:

   int[3] x=[1,2,3]; 
   fun(x);

Instead we propose the syntax:

   auto x=[1,2,3]S; 

where S stands for static. More generally the compiler should translate

 [x1,...,xn]S to: typeof(x1)[n]

Advantages:

- static array literals becomes as convenient as dynamic ones - no confusion possible for the compiler; I believe this syntax doesn’t clash with existing syntax. - In our previous example, no need to write an intermediate x: we can just write 

   fun([1,2,3]S);
   fun([1.0,2,3]S); //for example, if static array of doubles requested 
   void fun(T...)(T x){} which accept fun(1,2,3): one could just write:
   void fun(T,uint N)(in T[N]x){} or void fun(T,uint N)(T[N]x){}

This should be simpler than a previous request I’ve seen for int[$]x=[1,2,3]; which still requires one to write the type explicitly.

This document has been placed in the Public Domain.