Automatic static array length
Adam D. Ruppe
destructionator at gmail.com
Wed Dec 26 22:36:38 UTC 2018
On Wednesday, 26 December 2018 at 22:23:02 UTC, Your Name wrote:
> Is there a way to declare a static array with an automatic
> length, so that it doesn't have to be manually calculated?
Yes, there is a library function from std.array:
http://dpldocs.info/experimental-docs/std.array.staticArray.1.html
---
import std.array;
auto a = [0, 1].staticArray; // usage here, note auto
static assert(is(typeof(a) == int[2]));
assert(a == [0, 1]);
---
Though, if you want static allocation but not necessarily static
type, you can also just use... the static keyword!
static int[] a = [1, 2, 3];
That would be typed int[], of course, but it would have size 3
there and would be in a statically allocated block (which also
means btw the array is evaluated at compile time, and thus
subject to those rules).
So depends on exactly what you need, I'm guessing that lib
function is it, but you should consider the static keyword option
too as it is a good pattern to know anyway.
More information about the Digitalmars-d
mailing list