DIP 1025--Dynamic Arrays Only Shrink, Never Grow--Community Review Round 1

jmh530 john.michael.hall at gmail.com
Tue Nov 12 15:59:57 UTC 2019


On Tuesday, 12 November 2019 at 13:10:06 UTC, Guillaume Piolat 
wrote:
> [snip]
>
> I don't know.
> C++ has std::vector and std::string_view, but our slices do 
> these two things. It makes things easier sometimes but in the 
> end you have to track ownership in your head, especially if you 
> use @nogc and -betterC.
>
> Does "dynamic arrays ARE slices" really hurt us?
>
> [snip]

I keep getting a little mixed up when referring to slices and 
dynamic arrays. So some
T[] x;
is a dynamic array and
auto y = x[a..b];
or
auto y = x[];
is a slicing operation on x. And right now, slicing x also 
returns a dynamic array unless there is some opSlice defined that 
does something different.

So one option would be to keep dynamic arrays as they are and 
change the slicing operations to return a slice type. They would 
be like dynamic arrays with the exception that you can't append 
to them or change the length. However, this would probably lead 
to a lot of breakage, even if you could have a .array function 
that can easily convert a slice to an array.

What about instead something like below with a type that has 
appending disabled. I had tried to make length const, but I 
figured it was easier to just return data's length. I'm not sure 
if this works in the more general case though. Regardless, the 
benefit is that this is completely opt-in and requires no 
code-breakage.

```
struct View(T : U[], U) {
     T data;
     alias data this;

     this(T x) {
      	data = x;
     }

     @disable void opOpAssign(string op)(U rhs)
         if (op == "~")
     {
         data ~= rhs;
     }

     @disable void opOpAssign(string op)(U[] rhs)
         if (op == "~")
     {
         data ~= rhs;
     }

     @disable T[] opBinary(string op)(U rhs)
         if (op == "~")
     {
         return data ~ rhs;
     }

     @disable T[] opBinary(string op)(U[] rhs)
         if (op == "~")
     {
         return data ~ rhs;
     }

     size_t length() {
      	return data.length;
     }
}

auto view(T : U[], U)(T x) {
	return View!(T, U)(x);
}

void main() {
     int[] x = [0, 3, 5];
     auto y = x[0..2].view;
}
```


More information about the Digitalmars-d mailing list