Slices and Dynamic Arrays
Steven Schveighoffer
schveiguy at yahoo.com
Sun Dec 31 12:44:26 UTC 2017
On 12/30/17 8:57 PM, Tony wrote:
> For me, it is confusing to use "slice" and "dynamic array" as synonyms.
> My initial impression was that they must have different code underlying
> them, and different behavior.
As stated in the slices article, I think of them as separate -- the
slice is the public type that is used to operate on dynamic arrays, the
dynamic array is a nameless type that only exists in the runtime. It
helped me immensely when rewriting the array runtime to think of it that
way. All the feedback I received when publishing the article was along
the lines of "Wow, thinking of it that way helps a lot", so I think it's
a good mental model.
But in terms of D types, the slice *is* the dynamic array type, it
behaves in all the ways you would expect a dynamic array type to behave.
The only difference is that a slice does not own the memory it
references. Normally you would consider a dynamic array to own its
memory (i.e. be responsible for allocation and destruction). Because we
have the GC, ownership can be fuzzy.
> The DLang Tour has a section on Slices that says in bold "Slices and
> dynamic arrays are the same". I think that sentence deserves an
> explanation as to why there are two terms being utilized for the same
> thing. I would prefer that "slice" as a noun was used only for the time
> when a dynamic array was initialized from a slice of another array. Or
> better yet - slice was never used as a noun - only a verb or adjective:
> took a slice of array A to form a slice dynamic array B (or
> slice-intialized dynamic array B).
The question really is, what is the name of the type T[]? If you give it
a different name depending on how it was created, then you have all
sorts of confusion. In fact, there was a proposal by Walter and Andrei a
long long time ago to have a type T[new] which would be the dynamic
array type, and T[] be the slice type. This failed, because in Andrei's
words, "Explaining two very similar but subtly different types to
newcomers is excruciatingly difficult."
IMO, T[] is a slice, because it may not be GC-backed dynamic array data
underneath. Some people prefer to think of it as a dynamic array,
because you can use it like a dynamic array no matter what it points at.
Either way works, and fits the implementation. It's really a matter of
preference.
-Steve
More information about the Digitalmars-d-learn
mailing list