September 05, 2014 Mutable array with fixed length | ||||
---|---|---|---|---|
| ||||
How would you create a mutable array with a fixed(compile error when trying to change) length. |
September 05, 2014 Re: Mutable array with fixed length | ||||
---|---|---|---|---|
| ||||
Posted in reply to Freddy | On Fri, 05 Sep 2014 00:26:07 +0000 Freddy via Digitalmars-d-learn <digitalmars-d-learn@puremagic.com> wrote: > How would you create a mutable array with a fixed(compile error > when trying to change) length. Static arrays have a fixed length and live on the stack. int[12] arr; Dynamic arrays have a mutable length and the memory that they refer to normally lives on the heap (though they can be slices of static arrays or any two pointers). int[] arr = new int[](12); If the array is fully const or immutable immutable(int[]) arr = new immutable(int[])(12); then its length can't be mutated, whereas if the elements are const or immutable but the array is not const(int)[] = new const(int)[](12); then the length can mutated but the elements cannot be. However, because const and immutable are transitive, there is no way to have an array whose elements are mutable but have the array itself (and thus its length) be const or immutable. So, to get what you want, you're probably going to have to create a wrapper struct that forwards all of the operations that you want and doesn't expose the ones you don't (e.g. length). - Jonathan M Davis |
Copyright © 1999-2021 by the D Language Foundation