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

Salih Dincer salihdb at hotmail.com
Thu Oct 5 20:59:47 UTC 2023


On Thursday, 5 October 2023 at 16:40:49 UTC, Gaurav Negi wrote:
> Well, in the D programming language, both opIndex and opSlice 
> are two different operators used to access elements of a custom 
> type.

Yeah, D is on its way to becoming a near-perfect programming 
language...

```d
enum initialSituation = [1, 2, 3];
import std.stdio;

void main()
{
   auto s = S(initialSituation);

   s[] = 1;
   s[1] = 2;
   s[2] += 2;
   
   assert(s.arr == initialSituation);

   auto d = s *= 2;
   
   assert(d == S([2, 4, 6]));
}
/* Prints:
[1, 1, 1]: onlineapp.S.opSliceAssign
[1, 2, 1]: onlineapp.S.opIndexAssign
[1, 2, 1]: onlineapp.S.opIndex
[2, 4, 6]: onlineapp.S.opOpAssign!"*".opOpAssign
*/

struct S
{
   int[] arr;

   auto opSliceAssign (int value)
   {
     scope(exit)
     {
       writefln("%s: %s", arr, __FUNCTION__);
     }
     return arr[] = value;
   }

   auto opIndexAssign(int value, int index)
   {
     scope(exit)
     {
       writefln("%s: %s", arr, __FUNCTION__);
     }
     arr[index] = value;
   }

   ref opIndex(size_t index)
   {
     scope(exit)
     {
       writefln("%s: %s", arr, __FUNCTION__);
     }
     return arr[index];
   }

   ref opOpAssign(string op)(int value)
   {
     scope(exit)
     {
       writefln("%s: %s", arr, __FUNCTION__);
     }
     mixin("arr[] " ~ op ~ "=value;");
     return this;
   }
}
```

SDB at 79


More information about the Digitalmars-d-learn mailing list