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

Gaurav Negi gauravbackliner at gmail.com
Thu Oct 5 16:40:49 UTC 2023


Well, in the D programming language, both opIndex and opSlice are 
two different operators used to access elements of a custom type.

     struct S(T)
     {
         T[] arr;

         T opIndex(size_t index) const
         {
             assert(index < arr.length, "Index out of range");
             return arr[index];
         }

         T[] opSlice(size_t startIndex, size_t endIndex) const
         {
             assert(startIndex <= endIndex && endIndex <= 
arr.length, "Invalid slice indices");
             return arr[startIndex..endIndex];
         }
     }

     alias Type = int;
     void main()
     {
         auto s = S!Type([1, 2, 3]);

         auto element = s[0]; // Calls s.opIndex()
         assert(element == 1);

         auto slice = s[1..3]; // Calls s.opSlice()
         assert(slice == [2, 3]);
     }

Thanks


More information about the Digitalmars-d-learn mailing list