The difference between T[] opIndex() and T[] opSlice()

Jonathan M Davis newsgroup.d at jmdavisprog.com
Mon Oct 2 02:01:34 UTC 2023


On Sunday, October 1, 2023 11:51:17 AM MDT Salih Dincer via Digitalmars-d-
learn wrote:
> On Sunday, 1 October 2023 at 17:41:08 UTC, Salih Dincer wrote:
> > Also, is it correct to use [] when returning?
> >
> > Thanks...
>
> [Here](https://dlang.org/spec/operatoroverloading.html#slice),
> the opIndex() is proposed and an example of parameterized the
> opSlice() is given for multidimensional arrays.  Like there's no
> difference, huh?
>
> Puff :)

I suspect that the only people who really understand the full mess with
opIndex and opSlice at this point are the folks who have done a bunch with
multi-dimensional containers, which fortunately, I haven't had to deal with
any time recently, so I'm not well-versed on all of the nitty-gritty
details.

The situation used to be a bit clearer, but folks wanted better support for
multi-dimensional containers, so some changes were made. The result is that
if you're dealing with multiple arguments, the difference in which is called
should come down to whether you're using the slice operator between indices
- .. - or whether you're using commas (though since you can mix and match to
an extent with multi-dimensional containers, it's still pretty confusing
IMHO). Either way, when you have no arguments, the situation is certainly
more confusing than it used to be.

Previously, you would have always used opSlice with no parameters for
something like returning the full slice of a container, but I think that
it's now possible to do exactly the same thing with opIndex (confusing as
that may be), because that made some sense when writing a variadic opIndex.

For most code, you'd just write an opIndex with a single parameter for
indexing an element, opSlice with two parameters for slicing the range or
container, and then either opIndex or opSlice with no parameters to return a
slice of the entire container (in which case, personally, I'd use opSlice,
because semantically, that's what you're doing, but either should work IIRC).

- Jonathan M Davis





More information about the Digitalmars-d-learn mailing list